-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathprofiles.js
More file actions
264 lines (248 loc) · 11.6 KB
/
profiles.js
File metadata and controls
264 lines (248 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/* prettier-ignore */
/*
* profiles.js
*
* This module defines functions that implement the concept of profiles
*
* A machine profile is a collection of settings, macros, and apps that can be loaded
* to realize a sensible default machine state.
*
* System profiles are packaged with the fabmo-engine - they live in the /profiles directory
* at the top level. Like other mutable parts of the engine, profiles are copied to the
* /opt/fabmo directory on startup, and hosted from there, ultimately.
*
* When a profile is selected, the machine's macros, settings, and apps are obliterated,
* and subsequently replaced with the profile contents. When this is done, the engine
* is restarted so the configurations are loaded "fresh"
*
* Profiles are identified by their package.json, which includes (minimally) a name and description
* Configuration files that are included with a profile are merged with default configurations
* when profile data is copied over. (If a profile specifies a config value it is used, but if
* not, the default is used instead.)
*
* The 'default' profile comes with the engine source - it is the fallback if no other profile is selected
* and it is the start point for building out the configs that may be modified when the specific profile is
* applied.
*/
var config = require("./config");
var async = require("async");
var fs = require("fs-extra");
var log = require("./log").logger("profiles");
var ncp = require("ncp").ncp;
var path = require("path");
var util = require("./util");
var snapshots = require("./snapshots");
// Directories affected by profiles
var PROFILE_DIRS = ["config", "macros", "apps"];
// Singleton collection of profiles
var profiles = {};
// Load all profiles from disk
// callback - gets a collection of profiles (name -> profile) or error
var load = function (callback) {
log.debug("Loading profiles...");
var profileDir = config.getDataDir("profiles");
// Copy profiles from ./profiles to the /opt/fabmo directory if they don't exist already
fs.readdir(profileDir, function (err, files) {
if (err) {
return callback(err);
}
fs.readdir("./profiles", function (err, localfiles) {
if (err) {
log.error(err);
} else {
localfiles = localfiles.filter(function (item) {
return !/(^|\/)\.[^/.]/g.test(item);
});
for (var i = 0; i < localfiles.length; i++) {
if (files.indexOf(localfiles[i]) === -1) {
try {
fs.copySync("./profiles/" + localfiles[i], profileDir + "/" + localfiles[i]);
files.push(localfiles[i]);
log.info("Copied " + localfiles[i] + " into opt");
} catch (err) {
log.error(err);
}
}
}
}
util.diskSync(function () {
async.each(
files,
function (file, callback) {
try {
var profilePath = path.join(profileDir, file);
fs.stat(profilePath, function (err, stats) {
if (err) callback(err);
if (stats.isDirectory()) {
readProfileInfo(profilePath, function (err, profile) {
try {
if (err) {
log.error(err);
} else {
log.debug("Read profile " + profile.name);
profiles[profile.name] = profile;
}
} catch (e) {
log.error(e);
}
callback(null);
});
} else {
callback(null);
}
});
} catch (e) {
log.error(e);
}
},
function allDone() {
callback(null, profiles);
}
);
});
});
});
};
// Read the package.json from the provided profile directory and return an info object that
// includes the profile info included in the json file, plus the profile directory
// profileDir - full path of a profile directory
// callback - Gets the profile info object, or error:
// eg: {name :'Desktop MAX', description : 'A 24x18" supertool', dir:'/opt/fabmo/profiles/Desktop MAX'}
var readProfileInfo = function (profileDir, callback) {
fs.readFile(path.join(profileDir, "package.json"), "utf8", function (err, data) {
if (err) return callback(new Error("Could not read profile package.json: " + err));
try {
var obj = JSON.parse(data);
} catch (e) {
return callback(new Error("Profile " + profileDir + " does not have a valid package.json"));
}
if (!obj["name"]) throw new Error("Profile package.json does not have a name");
callback(null, {
name: obj["name"],
description: obj["description"] || "",
dir: profileDir,
});
});
};
// This handling of the initial profile and the shift to the selected profile is pretty convoluted and
// ... could use some refactoring. But, for the momement is seems relaible.
// Apply the named profile handling whether we are the default or the user selected profile that builds on default.
// profileName - The name of the profile to apply. Must be one of the loaded profiles
// callback - Gets an error if there was a problem.
var apply = function (profileName, callback) {
if (profileName in profiles) {
log.debug("Switching profiles to " + profileName);
// Get the profile data
var profile = profiles[profileName];
// Check if this is an auto-profile application
var profileDef = require("./config/profile_definition");
var isAutoProfile = profileDef.isChangeInProgress() || profileDef.hasAutoProfileDefinition();
// During auto-profile setup, config files are already complete from config loading
// Only copy macros and apps, not config files
var dirsToProcess = isAutoProfile ? ["macros", "apps"] : PROFILE_DIRS;
if (isAutoProfile) {
log.info("Auto-profile application - skipping config directory (already complete)");
}
// Snapshot the current state before the destructive copy. If the
// user (or we) made a mistake choosing the profile, restoring from
// the auto-snapshot rolls back the change. Best-effort: failures
// are logged and do not block the profile change itself.
snapshots.createAuto("auto_pre_profile", function (snapErr) {
if (snapErr) {
log.warn("auto_pre_profile snapshot failed (continuing): " + snapErr.message);
}
doApply();
});
function doApply() {
// For every directory affected by profiles...
// Use eachSeries to copy directories sequentially (avoids I/O race conditions)
async.eachSeries(
dirsToProcess, // ← Use filtered list instead of PROFILE_DIRS
function (dir, callback) {
var configDir = config.getDataDir(dir);
var profileConfigDir = path.join(profile.dir, dir);
var authSecretExists = false;
var authPath = configDir + "/auth_secret";
log.debug("Removing config directory " + configDir);
//if auth_secret file exists lets copy it to a tmp directory
if (fs.existsSync(authPath)) {
authSecretExists = true;
try {
fs.ensureDirSync("/opt/fabmo/tmp");
fs.copySync(authPath, "/opt/fabmo/tmp/auth_secret");
} catch (e) {
log.warn(e);
}
} else {
log.debug("Auth secret doesnt already exist");
}
// Trash the directory in the data directory
fs.remove(configDir, function (err) {
if (err) {
return callback(err);
}
// ...and replace it with the configuration provided by the profile
log.debug("Copying profile configuration directory " + profileConfigDir);
// Use fs.copy (fs-extra) instead of ncp for more reliable recursive copy
fs.copy(profileConfigDir, config.getDataDir(dir), function (err) {
if (err) {
log.error("Failed to copy profile directory " + profileConfigDir + ": " + err.message);
return callback(err);
}
log.debug("...done copying " + dir + ".");
// Copy auth secret back if we moved it.
if (authSecretExists) {
fs.copySync("/opt/fabmo/tmp/auth_secret", authPath);
fs.remove("/opt/fabmo/tmp", function (err) {
if (err) {
log.error(err);
} else {
log.debug("copied auth_secret and removed tmp dir");
}
});
}
callback();
});
});
},
function allDone(err) {
if (err) {
log.error("Error during profile directory copy: " + err.message);
return callback(err);
}
config.clearAppRoot(function (clearErr) {
if (clearErr) {
log.warn("Failed to clear approot: " + clearErr);
}
var appsDir = config.getDataDir("apps");
fs.readdir(appsDir, function (err, files) {
if (files) {
files.forEach(function (file) {
fs.renameSync(
path.join(appsDir, file),
path.join(appsDir, util.createUniqueFilename(file))
);
});
util.diskSync(function () {
callback(null);
});
} else {
util.diskSync(function () {
callback(null, "no apps"); // TODO : What is this 'no apps' thing?
});
}
});
});
}
);
}
} else {
log.warn(profileName + ", user selected profile.");
callback(null, "not default profile"); // Continue without error
}
};
module.exports.load = load;
module.exports.apply = apply;
module.exports.getProfiles = function () {
return profiles;
};