This repository has been archived by the owner on May 12, 2021. It is now read-only.
/
fakebackend.js
2114 lines (1937 loc) · 72.8 KB
/
fakebackend.js
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
General Public License for more details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
/**
An in-memory fake Juju backend and supporting elements.
@module env
@submodule env.fakebackend
*/
YUI.add('juju-env-fakebackend', function(Y) {
var models = Y.namespace('juju.models');
var ziputils = Y.namespace('juju.ziputils');
var viewUtils = Y.namespace('juju.views.utils');
var DEFAULT_CHARM_ICON_PATH = 'static/img/charm_160.svg';
var VALUE_ERROR = {error: 'Unparsable environment data.'};
var UNAUTHENTICATED_ERROR = {error: 'Please log in.'};
/**
An in-memory fake Juju backend.
@class FakeBackend
*/
function FakeBackend(config) {
// Invoke Base constructor, passing through arguments.
FakeBackend.superclass.constructor.apply(this, arguments);
}
FakeBackend.NAME = 'fake-backend';
FakeBackend.ATTRS = {
authenticated: {value: false},
authorizedUsers: {value: {'admin': 'password'}},
defaultSeries: {value: 'precise'},
name: {value: 'Environment'},
maasServer: {value: null},
providerType: {value: 'demonstration'},
store: {required: true},
token: {value: 'demoToken'}
};
Y.extend(FakeBackend, Y.Base, {
/**
Initializes.
@method initializer
@return {undefined} Nothing.
*/
initializer: function() {
this.db = new models.Database();
this._resetChanges();
this._resetAnnotations();
// used for relation id's
this._relationCount = 0;
// used for deployer import tracking
this._importId = 0;
this._importChanges = [];
this._deploymentId = 0;
},
/**
Reset the database for reporting object changes.
@method _resetChanges
@return {undefined} Nothing.
*/
_resetChanges: function() {
this.changes = {
// These are hashes of identifier: [object, boolean], where a true
// boolean means added or changed and a false value means removed.
services: {},
machines: {},
units: {},
relations: {}
};
},
/**
Return all of the recently changed objects.
@method nextChanges
@return {Object} A hash of the keys 'services', 'machines', 'units' and
'relations'. Each of those are hashes from entity identifier to
[entity, boolean] where the boolean means either active (true) or
removed (false).
*/
nextChanges: function() {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var result;
if (Y.Object.isEmpty(this.changes.services) &&
Y.Object.isEmpty(this.changes.machines) &&
Y.Object.isEmpty(this.changes.units) &&
Y.Object.isEmpty(this.changes.relations)) {
result = null;
} else {
result = this.changes;
this._resetChanges();
}
return result;
},
/**
Reset the database for reporting object annotation changes.
@method _resetAnnotations
@return {undefined} Nothing.
*/
_resetAnnotations: function() {
this.annotations = {
// These are hashes of identifier: object.
services: {},
machines: {},
units: {},
relations: {},
annotations: {}
};
},
/**
Return all of the recently annotated objects.
@method nextAnnotations
@return {Object} A hash of the keys 'services', 'machines', 'units',
'relations' and 'annotations'. Each of those are hashes from entity
identifier to entity.
*/
nextAnnotations: function() {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var result;
if (Y.Object.isEmpty(this.annotations.services) &&
Y.Object.isEmpty(this.annotations.machines) &&
Y.Object.isEmpty(this.annotations.units) &&
Y.Object.isEmpty(this.annotations.relations) &&
Y.Object.isEmpty(this.annotations.annotations)) {
result = null;
} else {
result = this.annotations;
this._resetAnnotations();
}
return result;
},
/**
Attempt to log a user in.
@method login
@param {String} username The id of the user.
@param {String} submittedPassword The user-submitted password.
@return {Bool} True if the authentication was successful.
*/
login: function(username, submittedPassword) {
var password = this.get('authorizedUsers')[username],
authenticated = password === submittedPassword;
this.set('authenticated', authenticated);
return authenticated;
},
/**
Attempt to log a user in with a token.
@method tokenlogin
@param {String} submittedToken The authentication token.
@return {Array} [username, password] if successful, or else undefined.
*/
tokenlogin: function(submittedToken) {
var token = this.get('token'),
authorizedUsers = this.get('authorizedUsers'),
authenticated = token === submittedToken;
this.set('authenticated', authenticated);
if (authenticated) {
var username = Object.keys(authorizedUsers)[0];
var password = authorizedUsers[username];
return [username, password];
}
},
/**
Log out. If already logged out, no error is raised.
@method logout
@return {undefined} Nothing.
*/
logout: function() {
this.set('authenticated', false);
},
/**
Deploy a service from a charm. Uses a callback for response!
@method deploy
@param {String} charmUrl The URL of the charm.
@param {Function} callback A call that will receive an object either
with an "error" attribute containing a string describing the problem,
or with a "service" attribute containing the new service, a "charm"
attribute containing the charm used, and a "units" attribute
containing a list of the added units. This is asynchronous because we
often must go over the network to the charm store.
@param {Object} options An options object.
name: The name of the service to be deployed, defaulting to the charm
name.
config: The charm configuration options, defaulting to none.
configYAML: The charm configuration options, expressed as a YAML
string. You may provide only one of config or configYAML.
unitCount: The number of units to be deployed.
toMachine: The machine/container specification to which the service
should be deployed.
@return {undefined} All results are passed to the callback.
*/
deploy: function(charmId, callback, options) {
if (!this.get('authenticated')) {
return callback(UNAUTHENTICATED_ERROR);
}
if (!options) {
options = {};
}
var self = this;
this._loadCharm(charmId, {
// On success deploy the successfully-obtained charm.
success: function(charm) {
self._deployFromCharm(charm, callback, options);
},
failure: callback
});
},
/**
Return a promise to deploy a charm. On failure the promise will be
rejected.
@method promiseDeploy
@param {String} charmId Charm to deploy.
@param {Object} [options] See deploy.
@return {Promise} Resolving to the results of the deploy call.
*/
promiseDeploy: function(charmId, options) {
var self = this;
return new Y.Promise(function(resolve, reject) {
var intermediateCallback = function(result) {
if (result.error) {
reject(result);
} else {
resolve(result);
}
};
self.deploy(charmId, intermediateCallback, options);
});
},
/**
Set the given service to use the given charm, optionally forcing units in
error state to use the charm.
@method setCharm
@param {String} serviceName The name of the service to set.
@param {String} charmId The charm to use.
@param {Boolean} force Whether or not to force the issue.
@param {Function} callback A call that will receive an object, potentially
with an "error" attribute containing a string describing the problem.
@return {undefined} All results are passed to the callback.
*/
setCharm: function(serviceName, charmId, force, callback) {
if (!this.get('authenticated')) {
return callback(UNAUTHENTICATED_ERROR);
}
var self = this;
var service = this.db.services.getById(serviceName);
if (!service) {
return callback({error: 'Service "' + serviceName + '" not found.'});
}
var unitsInError = service.get('units')
.some(function(unit) {
return (/error/).test(unit.agent_state);
});
if (unitsInError && !force) {
return callback({error: 'Cannot set charm on a service with units in ' +
'error without the force flag.'});
}
this._loadCharm(charmId, {
success: function(charm) {
service.set('charm', charm.get('id'));
self.changes.services[service.get('id')] = [service, true];
callback({});
},
failure: callback
});
},
/**
Get a charm from a URL, via the charmworld API and/or db. Uses callbacks.
@method _loadCharm
@param {String} charmId The URL of the charm.
@param {Function} callbacks An optional object with optional success and
failure callables. This is asynchronous because we
often must go over the network to the charm store. The success
callable receives the fully loaded charm, and the failure callable
receives an object with an explanatory "error" attribute.
@return {undefined} Use the callbacks to handle success or failure.
*/
_loadCharm: function(charmId, callbacks) {
var charmIdParts = models.parseCharmId(
charmId, this.get('defaultSeries'));
if (!callbacks) {
callbacks = {};
}
if (!charmIdParts) {
return (
callbacks.failure &&
callbacks.failure({error: 'Invalid charm id: ' + charmId}));
}
var charm = this.db.charms.getById(charmId);
if (charm) {
callbacks.success(charm);
} else {
// Get the charm data.
var self = this;
this.get('store').charm(charmIdParts.storeId, {
// Convert the charm data to a charm and use the success
// callback.
success: function(data) {
var charm = self._getCharmFromData(data.charm || data);
if (callbacks.success) {
callbacks.success(charm);
}
},
// Inform the caller of an error using the charm store.
failure: function(e) {
// This is most likely an IOError stemming from an
// invalid charm pointing to a bad URL and a read of a
// 404 giving an error at this level. IOError isn't user
// facing so we log the warning.
console.warn('error loading charm: ', e);
if (callbacks.failure) {
callbacks.failure(
{error: 'Error interacting with the charmworld API.'});
}
}
});
}
},
/**
Convert charm data as returned by the charmworld API into a charm.
The charm might be pre-existing or might need to be created, but
after this method it will be within the db.
@method _getCharmFromData
@param {Object} charmData The raw charm information as delivered by the
charmworld API.
@return {Object} A matching charm from the db.
*/
_getCharmFromData: function(charmData) {
var charm = this.db.charms.getById(charmData.store_url || charmData.url);
if (!charm) {
charmData.id = charmData.store_url || charmData.url;
charm = this.db.charms.add(charmData);
}
return charm;
},
/**
Deploy a charm, given the charm, a callback, and options.
@method _deployFromCharm
@param {Object} charm The charm to be deployed, from the db.
@param {Function} callback A call that will receive an object either
with an "error" attribute containing a string describing the problem,
or with a "service" attribute containing the new service, a "charm"
attribute containing the charm used, and a "units" attribute
containing a list of the added units. This is asynchronous because we
often must go over the network to the charm store.
@param {Object} options An options object.
name: The name of the service to be deployed, defaulting to the charm
name.
config: The charm configuration options, defaulting to none.
configYAML: The charm configuration options, expressed as a YAML
string. You may provide only one of config or configYAML.
unitCount: The number of units to be deployed.
toMachine: The machine/container specification to which the service
should be deployed.
@return {undefined} Get the result from the callback.
*/
_deployFromCharm: function(charm, callback, options) {
if (!options) {
options = {};
}
if (!options.name) {
options.name = charm.get('package_name');
}
if (this.db.services.getById(options.name)) {
console.log(options);
return callback({error: 'A service with this name already exists (' +
options.name + ').'});
}
if (options.configYAML) {
if (!Y.Lang.isString(options.configYAML)) {
console.log(options);
return callback(
{error: 'Developer error: configYAML is not a string.'});
}
try {
// options.configYAML overrides options.config in Go and Python
// implementations, so we do that here too.
options.config = jsyaml.safeLoad(options.configYAML);
} catch (e) {
if (e instanceof jsyaml.YAMLException) {
console.log(options, e);
return callback({error: 'Error parsing YAML.\n' + e});
}
throw e;
}
}
var constraints = {};
if (options.constraints) {
constraints = options.constraints;
}
var annotations = options.annotations || {};
// In order for the constraints to support the python back end this
// needs to be an array, so we are converting it back to an object
// here so that the GUI displays it properly.
var constraintsMap = {}, vals;
if (typeof constraints === 'string') {
// Determine the number of key-value pairs and try the old-style comma
// separator if not the same as the constraints length.
var numPairs = constraints.match(/=/g).length;
// Although comma-separation is deprecated, check it first as it
// allows easier parsing if a mix of commas and spaces is used.
var pairs = constraints.split(',');
if (numPairs !== pairs.length) {
pairs = constraints.split(' ');
}
constraints = pairs;
}
if (Y.Lang.isArray(constraints)) {
constraints.forEach(function(cons) {
vals = cons.split('=');
constraintsMap[vals[0].trim()] = vals[1].trim();
});
} else {
constraintsMap = constraints;
}
// We need to set charm default values for the options that have not
// been explicitly provided.
var charmOptions = charm.get('options') || {};
// "config" will hold the service's config values--it will be the
// result of this processing.
var config = {};
var explicitConfig = options.config || {};
Object.keys(charmOptions).forEach(function(key) {
var opt = charmOptions[key],
value = explicitConfig[key] || opt['default'],
type = opt.type;
// Need to cast string config values to their proper type.
if (typeof value === 'string' && type !== 'string') {
if (type === 'int') {
config[key] = parseInt(value, 10);
} else if (type === 'boolean') {
config[key] = (value.toLowerCase() === 'true');
} else if (type === 'float') {
config[key] = parseFloat(value);
}
} else {
config[key] = value;
}
});
var service = this.db.services.add({
id: options.name,
name: options.name,
charm: charm.get('id'),
constraints: constraintsMap,
exposed: false,
subordinate: charm.get('is_subordinate'),
annotations: annotations,
config: config
});
this.changes.services[service.get('id')] = [service, true];
if (Object.keys(annotations).length) {
this.annotations.services[service.get('id')] = service;
}
var unitCount = options.unitCount;
if (!Y.Lang.isValue(unitCount) && !charm.get('is_subordinate')) {
// This is the current behavior in both implementations.
unitCount = 1;
}
var response = {};
// Add units if requested.
if (unitCount !== 0) {
response = this.addUnit(options.name, unitCount, options.toMachine);
}
response.service = service;
callback(response);
},
/**
Add machines/containers to the environment.
@method addMachines
@param {Array} params A list of parameters for each machine/container
to be added. Each item in the list must be an object containing the
following keys (all optional):
- constraints {Object}: the machine constraints;
- jobs {Array}: the juju-core jobs to associate with the new machine
(defaults to env.machineJobs.HOST_UNITS, which enables unit hosting
capabilities to new machines);
- series {String}: the machine series (the juju-core default series
is used if none is specified);
- parentId {String}: when adding a new container, this parameter can
be used to place it into a specific machine, in which case the
containerType must also be specified (see below). If parentId is
not set when adding a container, a new top level machine will be
created to hold the container with given series, constraints, jobs;
- containerType {String}: the container type of the new machine
(e.g. "lxc").
@return {Object} Returns an object either with an "error" attribute
containing a string describing the problem, or with a "machines"
attribute containing a list of the added machines. Each added machine
is an object including the machine "name" and an optional "error".
*/
addMachines: function(params) {
// Only proceed if the user is authenticated.
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
// A global error is only returned if an internal juju problem occurs.
// The fake backend actually never set the value.
return {
machines: params.map(function(param) {
return this._addMachine(
param.parentId, param.containerType, param.series || 'precise',
param.constraints, param.jobs);
}, this)
};
},
/**
Add a machine.
Used internally by addMachines.
@method _addMachine
@param {String} parentId The name of the parent machine (optional).
@param {String} containerType The container type of the new machine
(e.g. "lxc", optional).
@param {String} series The machine OS version.
@param {Object} constraints The machine constraints.
@param {Array} jobs The juju-core jobs to associate with the new machine.
@return {Object} Returns an object either with an "error" attribute
containing a string describing the problem, or with a "name"
attribute representing the newly created machine name.
*/
_addMachine: function(parentId, containerType, series, constraints, jobs) {
var machines = this.db.machines;
var parent;
if (parentId) {
// The container type must be specified when adding containers.
if (!containerType) {
return {error: 'parent machine specified without container type'};
}
// Ensure the parent machine exists.
parent = machines.getById(parentId);
if (!parent) {
return {error: 'cannot add a new machine: machine ' + parentId +
' not found'};
}
}
if (containerType) {
// Ensure the parent machine supports the requested container type.
// For the fake backend purposes, just checking it's either "lxc" or
// "kvm" is sufficient.
if (containerType !== 'lxc' && containerType !== 'kvm') {
return {error: 'cannot add a new machine: machine ' + parentId +
' cannot host ' + containerType + ' containers'};
}
// If the parent id is not explicitly passed, create a new machine to
// host the requested container.
if (!parent) {
parentId = this._getNextMachineName();
parent = machines.add({
id: parentId,
agent_state: 'started',
// In the fake backend machines have no addresses.
addresses: [],
instance_id: 'fake-instance',
// Give to the parent machine the default hardware characteristics.
hardware: this._getHardwareCharacteristics(false),
jobs: ['JobHostUnits'],
life: 'alive',
series: series,
// For the fake backend purposes, each machine supports LXC and KVM
// containers.
supportedContainers: ['lxc', 'kvm']
});
this.changes.machines[parentId] = [parent, true];
}
}
// Create the new machine/container.
var name = this._getNextMachineName(parentId, containerType);
var machine = machines.add({
id: name,
agent_state: 'started',
// In the fake backend machines have no addresses.
addresses: [],
instance_id: 'fake-instance',
hardware: this._getHardwareCharacteristics(!!parentId, constraints),
jobs: jobs,
life: 'alive',
series: series,
// For the fake backend purposes, each machine supports LXC and KVM
// containers.
supportedContainers: ['lxc', 'kvm']
});
this.changes.machines[name] = [machine, true];
return {name: name};
},
/**
Return hardware characteristics suitable for the given constraints.
@method _getHardwareCharacteristics
@param {Bool} isContainer Whether to return hardware characteristics for
a container or a top level machine.
@param {Object} constraints The machine constraints (optional).
@return {Object} The hardware characteristics represented by an object
with the following fields: arch, cpuCores, cpuPower, mem and disk.
*/
_getHardwareCharacteristics: function(isContainer, constraints) {
var defaults = {
arch: 'amd64',
cpuCores: 1,
cpuPower: 100,
mem: 1740,
disk: 8192
};
constraints = constraints || {};
if (isContainer) {
// Containers' hardware characteristics only include the architecture.
return {arch: constraints.arch || defaults.arch};
}
if (Y.Object.isEmpty(constraints)) {
// Return the default hardware characteristics.
return defaults;
}
return {
arch: constraints.arch || defaults.arch,
cpuCores: constraints['cpu-cores'] || defaults.cpuCores,
cpuPower: constraints['cpu-power'] || defaults.cpuPower,
mem: constraints.mem || defaults.mem,
disk: constraints.disk || defaults.disk
};
},
/**
Return the next available machine/container name.
@method _getNextMachineName
@param {String} parentId The name of the parent machine (optional).
@param {String} containerType the container type of the new machine
(e.g. "lxc", optional).
@return {String} The name of the machine/container.
*/
_getNextMachineName: function(parentId, containerType) {
var parts = [];
if (parentId) {
parts.push(parentId);
} else {
parentId = null;
}
if (containerType) {
parts.push(containerType);
} else {
containerType = null;
}
var numbers = this.db.machines.filter(function(machine) {
return (machine.parentId === parentId &&
machine.containerType === containerType);
}).map(function(machine) {
return machine.number;
});
// If no machines are already present, add machine/container number 0.
var nextNumber = 0;
if (numbers.length) {
nextNumber = Math.max.apply(Math, numbers) + 1;
}
parts.push(nextNumber);
return parts.join('/');
},
/**
Remove existing machines/containers.
@method destroyMachines
@param {Array} names The names of the machines/containers to be removed.
Each name is a string: machine names are numbers, e.g. "1" or "42";
containers have the [machine name]/[container type]/[container number]
form, e.g. "2/lxc/0" or "1/kvm/42".
@param {Boolean} force Whether to force machines removal even if they
host units or containers.
@return {Object} A response including an "error" attribute if any
problems occurred.
*/
destroyMachines: function(names, force) {
var self = this;
// Only proceed if the user is authenticated.
if (!self.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
// Define an object mapping machine names to units they contain.
// This is done once here in order to avoid looping through the units
// model lists multiple times.
var machineUnitsMap = self.db.services.filterUnits(function(unit) {
return names.indexOf(unit.machine) !== -1;
}).reduce(function(result, unit) {
var machine = unit.machine;
if (result[machine]) {
result[machine].push(unit);
} else {
result[machine] = [unit];
}
return result;
}, Object.create(null));
var errors = [];
var destroyed = false;
names.forEach(function(name) {
var error = self._destroyMachine(name, force, machineUnitsMap);
if (error === null) {
destroyed = true;
} else {
errors.push(error);
}
});
var response = {};
if (errors.length) {
var msg;
if (destroyed) {
msg = 'some machines were not destroyed: ';
} else {
msg = 'no machines were destroyed: ';
}
response.error = msg + errors.join('; ');
}
return response;
},
/**
Remove a machine given its name.
Used internally by destroyMachines.
@method _destroyMachine
@param {Array} name The name of the machines/containers to be removed.
@param {Boolean} force Whether to force machine removal.
@param {Object} machineUnitsMap Key/value pairs mapping machine names to
assigned unit objects.
@return {String|Null} An error if the machine cannot be removed, or null
if the removal succeeded.
*/
_destroyMachine: function(name, force, machineUnitsMap) {
var machines = this.db.machines;
var machine = machines.getById(name);
// Ensure the machine to be destroyed exists in the database.
if (!machine) {
return 'machine ' + name + ' does not exist';
}
// Check if the machine hosts containers.
var descendants = machines.filterByAncestor(name);
if (descendants.length) {
if (!force) {
var descendantNames = descendants.map(function(descendant) {
return descendant.id;
});
return ('machine ' + name + ' is hosting containers ' +
descendantNames.join(', '));
}
// Remove all descendants from the database.
machines.remove(descendants);
descendants.forEach(function(descendant) {
this.changes.machines[descendant.id] = [descendant, false];
}, this);
}
// Check if the machine has assigned units.
var units = machineUnitsMap[name];
if (units) {
if (!force) {
var unitNames = units.map(function(unit) {
return unit.id;
});
return ('machine ' + name + ' has unit(s) ' + unitNames.join(', ') +
' assigned');
}
// Remove all units assigned to this machine.
units.forEach(function(unit) {
this.db.removeUnits(unit);
this.changes.units[unit.id] = [unit, false];
}, this);
}
// Everything went well for this machine, remove it from the database.
machines.remove(machine);
this.changes.machines[machine.id] = [machine, false];
return null;
},
/**
Destroy the named service.
@method destroyService
@param {String} serviceName to destroy.
@return {Object} results With err and service_name.
*/
destroyService: function(serviceName) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var service = this.db.services.getById(serviceName);
if (!service) {
return {error: 'Invalid service id: ' + serviceName};
}
// Remove all relations for this service.
var relations = this.db.relations.get_relations_for_service(service);
Y.Array.each(relations, function(rel) {
this.db.relations.remove(rel);
this.changes.relations[rel.get('relation_id')] = [rel, false];
}, this);
// Remove units for this service.
// get() on modelList returns the array of values for all children by
// default.
var unitNames = service.get('units').get('id');
var result = this.removeUnits(unitNames);
if (result.error && result.error.length > 0) {
console.log(result, result.error);
return {
error: 'Error removing units [' + unitNames.join(', ') +
'] of ' + serviceName
};
} else if (result.warning && result.warning.length > 0) {
console.log(result, result.warning);
return {
error: 'Warning removing units [' + unitNames.join(', ') +
'] of ' + serviceName
};
}
// And finally destroy and remove the service.
this.db.services.remove(service);
this.changes.services[serviceName] = [service, false];
service.destroy();
return {result: serviceName};
},
/**
* Get service attributes.
*
* @method getService
* @param {String} serviceName to get.
* @return {Object} Service Attributes..
*/
getService: function(serviceName) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var service = this.db.services.getById(serviceName);
if (!service) {
return {error: 'Invalid service id: ' + serviceName};
}
var serviceData = service.getAttrs();
if (!serviceData.constraints) {
serviceData.constraints = {};
}
var relations = this.db.relations.get_relations_for_service(service);
var rels = relations.map(function(r) {return r.getAttrs();});
// TODO: properly map relations to expected format rather
// than this passthrough. Pending on the add/remove relations
// branches that will need the same helper code.
serviceData.rels = rels;
return {result: serviceData};
},
/**
* Get Charm data.
*
* @method getCharm
* @param {String} charmName to get.
* @return {Object} charm attrs..
*/
getCharm: function(charmName, callback) {
if (!this.get('authenticated')) {
return callback(UNAUTHENTICATED_ERROR);
}
var formatCharm = function(charm) {
// Simulate a delay in the charm loading for testing.
var charmLoadDelay = 0;
if (window.flags.charmLoadDelay) {
charmLoadDelay = parseInt(window.flags.charmLoadDelay, 10);
}
setTimeout(function() {
callback({result: charm.getAttrs()});
}, charmLoadDelay);
};
this._loadCharm(charmName, {
success: formatCharm,
failure: callback});
},
/**
Add units to the given service.
@method addUnit
@param {String} serviceName The name of the service to be scaled up.
@param {Integer} numUnits The number of units to be added, defaulting
to 1.
@param {String} toMachine The machine/container where the unit will be
placed, or null/undefined to create a top level machine.
@return {Object} Returns an object either with an "error" attribute
containing a string describing the problem, or with a "units"
attribute containing a list of the added units.
*/
addUnit: function(serviceName, numUnits, toMachine) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var service = this.db.services.getById(serviceName);
if (!service) {
return {error: 'Service "' + serviceName + '" does not exist.'};
}
var isSubordinate = service.get('subordinate');
if (Y.Lang.isUndefined(numUnits)) {
numUnits = isSubordinate ? 0 : 1;
}
if (!Y.Lang.isNumber(numUnits) ||
(!isSubordinate && numUnits < 1 ||
(isSubordinate && numUnits !== 0))) {
return {
error: 'Invalid number of units [' + numUnits +
'] for service: ' + serviceName
};
}
if (!Y.Lang.isValue(service.unitSequence)) {
service.unitSequence = 0;
}
var unit, machine, machines;
if (Y.Lang.isValue(toMachine)) {
if (numUnits > 1) {
return {error: 'When deploying to a specific machine, the ' +
'number of units requested must be 1.'};
}
// A specific machine is being targeted for the deploy.
var targetMachine = this.db.machines.getById(toMachine);
if (targetMachine === null) {
return {error: 'no machine matching ' + toMachine + ' found'};
}
machines = [targetMachine];
} else {
// Any machine will do; find or create one.
// Required machine changes are added by _getUnitMachines.
machines = this._getUnitMachines(numUnits);
}
var units = [];
for (var i = 0; i < numUnits; i += 1) {
var unitId = service.unitSequence;
machine = machines[i];
unit = this.db.addUnits({
'id': serviceName + '/' + unitId,
'machine': machine.id,
// The models use underlines, not hyphens (see
// app/models/models.js in _process_delta.)
'agent_state': 'started',
subordinate: isSubordinate
});
units.push(unit);