-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathprofile-api-service.js
More file actions
executable file
·493 lines (448 loc) · 18.5 KB
/
profile-api-service.js
File metadata and controls
executable file
·493 lines (448 loc) · 18.5 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Copyright © 2017 Dell Inc. or its subsidiaries. All Rights Reserved.
'use strict';
var di = require('di'),
ejs = require('ejs');
module.exports = profileApiServiceFactory;
di.annotate(profileApiServiceFactory, new di.Provide('Http.Services.Api.Profiles'));
di.annotate(profileApiServiceFactory,
new di.Inject(
'Promise',
'Http.Services.Api.Workflows',
'Protocol.Task',
'Protocol.Events',
'Services.Waterline',
'Services.Configuration',
'Services.Lookup',
'Logger',
'Errors',
'_',
'Profiles',
'Services.Environment',
'Http.Services.Swagger',
'Constants',
'Assert'
)
);
function profileApiServiceFactory(
Promise,
workflowApiService,
taskProtocol,
eventsProtocol,
waterline,
configFile,
lookupService,
Logger,
Errors,
_,
profiles,
Env,
swaggerService,
Constants,
assert
) {
var logger = Logger.initialize(profileApiServiceFactory);
function ProfileApiService() {
}
// Helper to convert property kargs into an ipxe friendly string.
ProfileApiService.prototype.convertProperties = function(properties) {
properties = properties || {};
if (properties.hasOwnProperty('kargs')) {
// This a promotion of the kargs property
// for DOS disks (or linux) for saving
// the trouble of having to write a
// bunch of code in the EJS template.
if(typeof properties.kargs === 'object') {
properties.kargs = _.map(
properties.kargs, function (value, key) {
return key + '=' + value;
}).join(' ');
}
} else {
// Ensure kargs is set for rendering.
properties.kargs = null;
}
return properties;
};
ProfileApiService.prototype.getMacs = function(macs) {
return _.flattenDeep([macs]);
};
/**
* Get macAddress in HTTP request
* @param {Object} query the query in HTTP request
* @param {String} requestIp the IP of the HTTP request
* @return {Promise} Resolves to macAddress if found, otherwise undefined.
*/
ProfileApiService.prototype.getMacAddressInRequest = function(query, requestIp) {
assert.object(query);
assert.string(requestIp);
if (query.macs && query.ips) {
var macAddresses = _.flattenDeep([query.macs]);
var ipAddresses = _.flattenDeep([query.ips]);
var index = _.findIndex(ipAddresses, function(ip) {
return (ip && (ip === requestIp));
});
if(index >= 0 && macAddresses[index]) {
return Promise.resolve(macAddresses[index]);
}
}
return Promise.resolve();
};
ProfileApiService.prototype.setLookup = function(ipAddress, macAddress, proxyIp, proxyPort) {
return lookupService.setIpAddress(ipAddress, macAddress)
.then(function() {
if (proxyIp) {
var proxy = 'http://%s:%s'.format(proxyIp, proxyPort);
return waterline.lookups.upsertProxyToMacAddress(proxy, macAddress);
}
});
};
ProfileApiService.prototype.getNode = function(macAddresses, options) {
var self = this;
return waterline.nodes.findByIdentifier(macAddresses)
.then(function (node) {
if (node) {
return node.discovered()
.then(function(discovered) {
if (!discovered) {
return taskProtocol.activeTaskExists(node.id)
.then(function() {
return node;
})
.catch(function() {
return self.runDiscovery(node, options);
});
} else {
// We only count a node as having been discovered if
// a node document exists AND it has any catalogs
// associated with it
return node;
}
});
} else {
return self.createNodeAndRunDiscovery(macAddresses, options);
}
});
};
ProfileApiService.prototype.runDiscovery = function(node, options) {
var self = this;
var configuration;
if (node.type === 'switch') {
configuration = self.getSwitchDiscoveryConfiguration(node, options.switchVendor);
} else {
var rebootCode = 1; //ipmi power cycle
var setObm = configFile.get('autoCreateObm', 'false');
var skipReboot = configFile.get('skipResetPostDiscovery', 'false');
if (skipReboot === 'true') {
rebootCode = 127; // skip reset but terminate bootstrap
}
if (setObm === 'true') {
skipReboot = 'true';
} else {
skipReboot = 'false';
}
var skipPollers = configFile.get('skipPollersCreation', 'false');
configuration = {
name: configFile.get('discoveryGraph', 'Graph.SKU.Discovery'),
options: {
defaults: {
graphOptions: {
target: node.id,
'skip-reboot-post-discovery' : {
skipReboot: skipReboot
},
'shell-reboot': {
rebootCode: rebootCode
}
},
nodeId: node.id
},
'skip-pollers': {
skipPollersCreation: skipPollers
},
'obm-option' : {
autoCreateObm: setObm
}
}
};
}
// If there is an api proxy add it to the context
lookupService.nodeIdToProxy(node.id).then( function(proxy) {
if(proxy) {
configuration.context = {proxy: proxy};
}
});
// The nested workflow holds the lock against the nodeId in this case,
// so don't add it as a target to the outer workflow context
return workflowApiService.createAndRunGraph(configuration, null)
.then(function() {
return self.waitForDiscoveryStart(node.id);
})
.then(function() {
return node;
});
};
ProfileApiService.prototype.getSwitchDiscoveryConfiguration = function(node, vendor) {
var configuration = {
name: 'Graph.SKU.Switch.Discovery.Active',
options: {
defaults: {
graphOptions: {
target: node.id
},
nodeId: node.id
},
'vendor-discovery-graph': {
graphName: null
}
}
};
vendor = vendor.toLowerCase();
if (vendor === 'cisco') {
configuration.options['vendor-discovery-graph'].graphName =
'Graph.Switch.Discovery.Cisco.Poap';
} else if (vendor === 'brocade') {
configuration.options['vendor-discovery-graph'].graphName =
'Graph.Switch.Discovery.Brocade.Ztp';
} else if (vendor === 'arista') {
configuration.options['vendor-discovery-graph'].graphName =
'Graph.Switch.Discovery.Arista.Ztp';
} else if (vendor === 'onie') {
configuration.options['vendor-discovery-graph'].graphName =
'Graph.Switch.Discovery.Dell.Onie';
} else if (vendor === 'dell') {
configuration.options['vendor-discovery-graph'].graphName =
'Graph.Switch.Discovery.Dell.Bmp';
} else {
throw new Errors.BadRequestError('Unknown switch vendor ' + vendor);
}
return configuration;
};
ProfileApiService.prototype.createNodeAndRunDiscovery = function(macAddresses, options) {
var self = this;
var node;
return Promise.resolve().then(function() {
return waterline.nodes.create({
name: macAddresses.join(','),
identifiers: macAddresses,
type: options.type
});
}).tap(function(_node) {
return eventsProtocol.publishNodeEvent(_node, 'added');
}).then(function (_node) {
node = _node;
return Promise.resolve(macAddresses).each(function (macAddress) {
return waterline.lookups.upsertNodeToMacAddress(node.id, macAddress);
});
})
.then(function () {
// Setting newRecord to true allows us to
// render the redirect again to avoid refresh
// of the node document and race conditions with
// the state machine changing states.
node.newRecord = true;
return self.runDiscovery(node, options);
});
};
// Quick and dirty extra two retries for the discovery graph, as the
// runTaskGraph promise gets resolved before the tasks themselves are
// necessarily started up and subscribed to bus events.
ProfileApiService.prototype.waitForDiscoveryStart = function(nodeId) {
var retryRequestProperties = function(error) {
if (error instanceof Errors.RequestTimedOutError) {
return taskProtocol.requestProperties(nodeId);
} else {
throw error;
}
};
return taskProtocol.requestProperties(nodeId)
.catch(retryRequestProperties)
.catch(retryRequestProperties);
};
ProfileApiService.prototype._handleProfileRenderError = function(errMsg, type, status) {
var err = new Error("Error: " + errMsg);
err.status = status || 500;
throw err;
};
ProfileApiService.prototype.getProfileFromTaskOrNode = function(node, vendor) {
var self = this;
var defaultProfile;
if (node.type === 'switch') {
// Unlike for compute nodes, we don't need to or have the capability
// of booting into a microkernel, so just send down the
// python script right away, and start downloading
// and executing tasks governed by the switch-specific
// discovery workflow.
if(vendor === 'onie'){
defaultProfile = 'dell-onie.sh';
} else if(vendor === 'dell'){
defaultProfile = 'dell-bmp.sh';
} else {
defaultProfile = 'taskrunner.py';
}
} else {
defaultProfile = 'redirect.ipxe';
}
return workflowApiService.findActiveGraphForTarget(node.id)
.then(function (taskgraphInstance) {
if (taskgraphInstance) {
return taskProtocol.requestProfile(node.id)
.catch(function(err) {
if (node.type === 'switch') {
return null;
} else {
throw err;
}
})
.then(function(profile) {
return [profile, taskProtocol.requestProperties(node.id)];
})
.spread(function (profile, properties) {
var _options;
if (node.type === 'compute') {
_options = self.convertProperties(properties);
} else if (node.type === 'switch') {
var switchVendor;
if(taskgraphInstance.injectableName === "Graph.Switch.Discovery.Arista.Ztp"){
switchVendor = "arista";
}else if(taskgraphInstance.injectableName === "Graph.Switch.Discovery.Brocade.Ztp"){
switchVendor = "brocade";
}else if(taskgraphInstance.injectableName === "Graph.Switch.Discovery.Cisco.Poap"){
switchVendor = "cisco";
} else if(taskgraphInstance.injectableName === "Graph.Switch.Discovery.Dell.Onie"){
switchVendor = "onie";
} else if(taskgraphInstance.injectableName === "Graph.Switch.Discovery.Dell.Bmp"){
switchVendor = "dell";
}
_options = {
identifier: node.id,
switchVendor : switchVendor
};
}
return {
profile: profile || defaultProfile,
options: _options,
context: taskgraphInstance.context
};
})
.catch(function (e) {
logger.warning("Unable to retrieve workflow properties or profiles", {
error: e,
id: node.id,
taskgraphInstanceId: taskgraphInstance.instanceId
});
return self._handleProfileRenderError(
'Unable to retrieve workflow properties or profiles', node.type, 503);
});
} else {
if (_.has(node, 'bootSettings')) {
if (_.has(node.bootSettings, 'options') &&
_.has(node.bootSettings, 'profile')) {
return {
profile: node.bootSettings.profile || 'redirect.ipxe',
options: node.bootSettings.options
};
} else {
return self._handleProfileRenderError(
'Unable to retrieve valid node bootSettings', node.type);
}
} else {
return {
profile: 'ipxe-info.ipxe',
options: { message:
'No active workflow and bootSettings, continue to boot' },
context: undefined
};
}
}
});
};
ProfileApiService.prototype.renderProfile = function (profile, req, res) {
var scope = res.locals.scope;
var options = profile.options || {};
var graphContext = profile.context || {};
var promises = [
swaggerService.makeRenderableOptions(req, res, graphContext,
profile.ignoreLookup),
profiles.get(profile.profile, true, scope)
];
if (profile.profile.endsWith('.ipxe')) {
promises.push(profiles.get('boilerplate.ipxe', true, scope));
}
return Promise.all(promises).spread(
function (localOptions, contents, boilerPlate) {
options = _.merge({}, options, localOptions);
// Render the requested profile + options. Don't stringify undefined.
return ejs.render((boilerPlate || '') + contents, options);
}
);
};
ProfileApiService.prototype.getProfiles = function(req, query, res) {
var self = this;
var ipAddress = res.locals.ipAddress;
return self.getMacAddressInRequest(query, ipAddress)
.then(function(macAddress) {
if(macAddress) {
res.locals.macAddress = macAddress;
var proxyIp = req.get(Constants.HttpHeaders.ApiProxyIp);
var proxyPort = req.get(Constants.HttpHeaders.ApiProxyPort);
return self.setLookup(ipAddress, macAddress, proxyIp, proxyPort);
}
})
.then(function() {
var macs = query.mac || query.macs;
if (macs) {
var macAddresses = self.getMacs(macs);
var options = {
type: 'compute'
};
return self.getNode(macAddresses, options)
.then(function (node) {
return self.getProfileFromTaskOrNode(node)
.then(function (render) {
return _.defaults(render, {
ignoreLookup: res.locals.macAddress ? true : false
});
});
});
} else {
return { profile: 'redirect.ipxe', ignoreLookup: true };
}
})
.catch(function (err) {
if (!err.status) {
throw new Errors.InternalServerError(err.message);
} else {
throw err;
}
});
};
ProfileApiService.prototype.getProfilesSwitchVendor = function(
requestIp, vendor
) {
var self = this;
return waterline.lookups.findOneByTerm(requestIp)
.then(function(record) {
return record.macAddress;
})
.then(function(macAddress) {
return self.getMacs(macAddress);
})
.then(function(macAddresses) {
var options = {
type: 'switch',
switchVendor: vendor
};
return self.getNode(macAddresses, options);
})
.then(function(node) {
return self.getProfileFromTaskOrNode(node, vendor);
})
.catch(function (err) {
throw err;
});
};
ProfileApiService.prototype.postProfilesSwitchError = function(error) {
logger.error('SWITCH ERROR DEBUG ', error);
};
return new ProfileApiService();
}