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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
|
/*
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 UNAUTHENTICATED_ERROR = {error: 'Please log in.'};
var VALUE_ERROR = {error: 'Unparsable environment data.'};
/**
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 = {
authorizedUsers: {value: {'admin': 'password'}},
authenticated: {value: false},
store: {required: true},
defaultSeries: {value: 'precise'},
providerType: {value: 'demonstration'}
};
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;
},
/**
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.
@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.'}));
}
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.
@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)) {
return callback({error: 'A service with this name already exists.'});
}
if (options.configYAML) {
if (!Y.Lang.isString(options.configYAML)) {
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) {
return callback({error: 'Error parsing YAML.\n' + e});
}
throw e;
}
}
var constraints = {};
if (options.constraints) {
constraints = options.constraints;
}
// 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') {
constraints = constraints.split(',');
}
if (Y.Lang.isArray(constraints)) {
constraints.forEach(function(cons) {
vals = cons.split('=');
constraintsMap[vals[0]] = vals[1];
});
} else {
constraintsMap = constraints;
}
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'),
// Because we only send the user changed options now
// we need to mix those values in to the charm config
// options when creating a new model.
config: (function() {
var charmOptions = charm.get('options') || {};
var config = {};
if (!options.config) { options.config = {}; }
Object.keys(charmOptions).forEach(function(key) {
config[key] =
options.config[key] ||
(charmOptions[key] ? charmOptions[key]['default'] : undefined);
});
return config;
})()
});
this.changes.services[service.get('id')] = [service, true];
var response = this.addUnit(options.name, options.unitCount);
response.service = service;
callback(response);
},
/**
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.'};
}
// 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.length > 0) {
return {error: 'Error removing units: ' + result.error};
} else if (result.warning.length > 0) {
return {error: 'Warning removing units: ' + result.warning};
}
// 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.'};
}
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.
@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) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var service = this.db.services.getById(serviceName);
if (!service) {
return {error: 'Service "' + serviceName + '" does not exist.'};
}
var is_subordinate = service.get('subordinate');
if (Y.Lang.isUndefined(numUnits)) {
numUnits = is_subordinate ? 0 : 1;
}
if (!Y.Lang.isNumber(numUnits) ||
(!is_subordinate && numUnits < 1 ||
(is_subordinate && numUnits !== 0))) {
return {error: 'Invalid number of units.'};
}
if (!Y.Lang.isValue(service.unitSequence)) {
service.unitSequence = 0;
}
var unit, machine;
var machines = this._getUnitMachines(numUnits);
var unitList = service.get('units');
var units = [];
for (var i = 0; i < numUnits; i += 1) {
var unitId = service.unitSequence;
machine = machines[i];
unit = unitList.add({
'id': serviceName + '/' + unitId,
'machine': machine.machine_id,
// The models use underlines, not hyphens (see
// app/models/models.js in _process_delta.)
'agent_state': 'started'
});
units.push(unit);
service.unitSequence += 1;
this.changes.units[unit.id] = [unit, true];
this.changes.machines[machine.machine_id] = [machine, true];
}
return {units: units, machines: machines};
},
/**
Find machines without any units currently assigned.
@method _getAvailableMachines
@return {Array} An array of zero or more machines that have been
previously allocated but that are not currently in use by a unit.
*/
_getAvailableMachines: function() {
var machines = [];
var usedMachineIds = {};
this.db.services.each(function(service) {
service.get('units').each(function(unit) {
if (unit.machine) {
usedMachineIds[unit.machine] = true;
}
});
});
this.db.machines.each(function(machine) {
if (!usedMachineIds[machine.machine_id]) {
machines.push(machine);
}
});
return machines;
},
/**
Find or allocate machines for the requested number of units.
@method _getUnitMachines
@param {Integer} count The number of units that need machines.
@return {Array} An array of [count] machines.
*/
_getUnitMachines: function(count) {
var machines = [];
var availableMachines = this._getAvailableMachines();
var machineId;
if (!Y.Lang.isValue(this.db.machines.sequence)) {
this.db.machines.sequence = 0;
}
for (var i = 0; i < count; i += 1) {
if (i < availableMachines.length) {
machines.push(availableMachines[i]);
} else {
machineId = this.db.machines.sequence += 1;
machines.push(
this.db.machines.add({
'machine_id': machineId.toString(),
'public_address':
'addr-' + machineId.toString() + '.example.com',
'agent_state': 'running'}));
}
}
return machines;
},
/**
Removes the supplied units
@method removeUnits
@param {Array} unitNames a list of unit names to be removed.
*/
removeUnits: function(unitNames) {
var service, removedUnit,
error = [],
warning = [];
// XXX: BradCrittenden 2013-04-15: Remove units should optionally remove
// the corresponding machines.
if (typeof unitNames === 'string') {
unitNames = [unitNames];
}
Y.Array.each(unitNames, function(unitName) {
service = this.db.services.getById(unitName.split('/')[0]);
if (service && service.get('is_subordinate')) {
error.push(unitName + ' is a subordinate, cannot remove.');
} else {
// For now we also need to clean up the services unit list but the
// above should go away soon when below becomes the default.
if (service) {
var units = service.get('units');
var unit = units.getById(unitName);
if (unit) {
units.remove(unit);
this.changes.units[unitName] = [unit, false];
return;
}
}
warning.push(unitName + ' does not exist, cannot remove.');
}
}, this);
// Return the errors and warnings
return {
error: error,
warning: warning
};
},
/**
Exposes a service from the supplied string.
@method expose
@param {String} serviceName The service name.
@return {Object} An object containing an `error` and `warning` properties
which will be undefined if there were no warnings or errors.
*/
expose: function(serviceName) {
var service = this.db.services.getById(serviceName),
warning, error;
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
if (service) {
if (!service.get('exposed')) {
service.set('exposed', true);
this.changes.services[service.get('id')] = [service, true];
} else {
warning = 'Service "' + serviceName + '" was already exposed.';
}
} else {
error = '"' + serviceName + '" is an invalid service name.';
}
return {
error: error,
warning: warning
};
},
/**
Unexposes a service from the supplied string.
@method unexpose
@param {String} serviceName The service name.
@return {Object} An object containing an `error` and `warning` properties
which will be undefined if there were no warnings or errors.
*/
unexpose: function(serviceName) {
var service = this.db.services.getById(serviceName),
warning, error;
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
if (service) {
if (service.get('exposed')) {
service.set('exposed', false);
this.changes.services[service.get('id')] = [service, true];
} else {
warning = 'Service "' + serviceName + '" is not exposed.';
}
} else {
error = '"' + serviceName + '" is an invalid service name.';
}
return {
error: error,
warning: warning
};
},
/**
Takes two string endpoints and splits it into usable parts.
@method parseEndpointStrings
@param {Database} db to resolve charms/services on.
@param {Array} endpoints an array of endpoint strings
to split in the format wordpress:db.
@return {Object} An Array of parsed endpoints, each containing name, type
and the related charm. Name is the user defined service name and type is
the charms authors name for the relation type.
*/
parseEndpointStrings: function(db, endpoints) {
return Y.Array.map(endpoints, function(endpoint) {
var epData = endpoint.split(':');
var result = {};
if (epData.length > 1) {
result.name = epData[0];
result.type = epData[1];
} else {
result.name = epData[0];
}
result.service = db.services.getById(result.name);
if (result.service) {
result.charm = db.charms.getById(
result.service.get('charm'));
if (!result.charm) {
console.warn('Failed to load charm',
result.charm, db.charms.size(), db.charms.get('id'));
}
} else {
console.warn('failed to resolve service', result.name);
}
return result;
}, this);
},
/**
Loops through the charm endpoint data to determine whether we have a
relationship match. The result is either an object with an error
attribute, or an object giving the interface, scope, providing endpoint,
and requiring endpoint.
@method findEndpointMatch
@param {Array} endpoints Pair of two endpoint data objects. Each
endpoint data object has name, charm, service, and scope.
@return {Object} A hash with the keys 'interface', 'scope', 'provides',
and 'requires'.
*/
findEndpointMatch: function(endpoints) {
var matches = [], result;
Y.each([0, 1], function(providedIndex) {
// Identify the candidates.
var providingEndpoint = endpoints[providedIndex];
// The merges here result in a shallow copy.
var provides = Y.merge(providingEndpoint.charm.get('provides') || {}),
requiringEndpoint = endpoints[!providedIndex + 0],
requires = Y.merge(requiringEndpoint.charm.get('requires') || {});
if (!provides['juju-info']) {
provides['juju-info'] = {'interface': 'juju-info',
scope: 'container'};
}
// Restrict candidate types as tightly as possible.
var candidateProvideTypes, candidateRequireTypes;
if (providingEndpoint.type) {
candidateProvideTypes = [providingEndpoint.type];
} else {
candidateProvideTypes = Y.Object.keys(provides);
}
if (requiringEndpoint.type) {
candidateRequireTypes = [requiringEndpoint.type];
} else {
candidateRequireTypes = Y.Object.keys(requires);
}
// Find matches for candidates and evaluate them.
Y.each(candidateProvideTypes, function(provideType) {
Y.each(candidateRequireTypes, function(requireType) {
var provideMatch = provides[provideType],
requireMatch = requires[requireType];
if (provideMatch &&
requireMatch &&
provideMatch['interface'] === requireMatch['interface']) {
matches.push({
'interface': provideMatch['interface'],
scope: provideMatch.scope || requireMatch.scope,
provides: providingEndpoint,
requires: requiringEndpoint,
provideType: provideType,
requireType: requireType
});
}
});
});
});
if (matches.length === 0) {
result = {error: 'Specified relation is unavailable.'};
} else if (matches.length > 1) {
result = {error: 'Ambiguous relationship is not allowed.'};
} else {
result = matches[0];
// Specify the type for implicit relations.
result.provides = Y.merge(result.provides);
result.requires = Y.merge(result.requires);
result.provides.type = result.provideType;
result.requires.type = result.requireType;
}
return result;
},
/**
Add a relation between two services.
@method addRelation
@param {String} endpointA A string representation of the service name
and endpoint connection type ie) wordpress:db.
@param {String} endpointB A string representation of the service name
and endpoint connection type ie) wordpress:db.
@param {Boolean} useRelationCount whether or not to generate and
incremented relation id or to just use the name and types of the
endpoints.
*/
addRelation: function(endpointA, endpointB, useRelationCount) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
if ((typeof endpointA !== 'string') ||
(typeof endpointB !== 'string')) {
return {error: 'Two string endpoint names' +
' required to establish a relation'};
}
// Parses the endpoint strings to extract all required data.
var endpointData = this.parseEndpointStrings(this.db,
[endpointA, endpointB]);
// This error should never be hit but it's here JIC
if (!endpointData[0].charm || !endpointData[1].charm) {
return {error: 'Charm not loaded.'};
}
// If there are matching interfaces this will contain an object of the
// charm interface type and scope (if supplied).
var match = this.findEndpointMatch(endpointData);
// If there is an error fetching a valid interface and scope
if (match.error) { return match; }
// Assign a unique relation id which is incremented after every
// successful relation if useRelationCount is set to true. If not, then
// it will be set with the requires/provides endpoint names.
var relationId = '';
if (useRelationCount) {
relationId = 'relation-' + this._relationCount;
} else {
relationId = [
match.requires.name + ':' + match.requires.type,
match.provides.name + ':' + match.provides.type
].join(' ');
}
// The ordering of requires and provides is stable in Juju Core, and not
// specified in PyJuju.
var endpoints = Y.Array.map(
[match.requires, match.provides],
function(endpoint) {
return [endpoint.name, {name: endpoint.type}];
});
// Explicit Role labelling.
endpoints[0][1].role = 'client';
endpoints[1][1].role = 'server';
var relation = this.db.relations.create({
relation_id: relationId,
type: match['interface'],
endpoints: endpoints,
pending: false,
scope: match.scope || 'global',
display_name: endpointData[0].type
});
if (relation) {
this._relationCount += 1;
// Add the relation to the change delta
this.changes.relations[relationId] = [relation, true];
// Because the sandbox can either be passed a string or an object
// we need to return as much information as possible to be able
// to rebuild the expected object for both situations.
// The only difference between this and the relation creation hash,
// above, is camelCase versus underlines. When we normalize on
// camelCase, we can simplify.
return {
relationId: relationId,
type: match['interface'],
endpoints: endpoints,
scope: match.scope || 'global',
displayName: endpointData[0].type,
relation: relation
};
}
// Fallback error If the relation was not able to be created
// for any reason other than what has already been checked for.
return false;
},
/**
Removes a relation between two services.
@method removeRelation
@param {String} endpointA A string representation of the service name
and endpoint connection type ie) wordpress:db.
@param {String} endpointB A string representation of the service name
and endpoint connection type ie) wordpress:db.
*/
removeRelation: function(endpointA, endpointB) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
if ((typeof endpointA !== 'string') ||
(typeof endpointB !== 'string')) {
return {error: 'Two string endpoint names' +
' required to establish a relation'};
}
// Parses the endpoint strings to extract all required data.
var endpointData = this.parseEndpointStrings(
this.db, [endpointA, endpointB]);
// This error should never be hit but it's here JIC
if (!endpointData[0].charm || !endpointData[1].charm) {
return {error: 'Charm not loaded.'};
}
var relation;
this.db.relations.some(function(rel) {
var endpoints = rel.getAttrs().endpoints;
return [0, 1].some(function(index) {
// Check to see if the service names match an existing relation
if ((endpoints[index][0] === endpointData[0].name) &&
(endpoints[!index + 0][0] === endpointData[1].name)) {
// Check to see if the interface names match
if ((endpoints[index][1].name === endpointData[0].type) &&
(endpoints[!index + 0][1].name === endpointData[1].type)) {
relation = rel;
return true;
}
}
});
});
if (relation) {
// remove the relation from the relation db model list
var result = this.db.relations.remove(relation);
// add this change to the delta
this.changes.relations[relation.get('id')] = [relation, false];
return result;
} else {
return {error: 'Relationship does not exist'};
}
},
/**
* Helper method to determine where to log annotation
* changes relative to a given entity.
*
* @method _getAnnotationGroup
* @param {Object} entity to track.
* @return {String} Annotation group name (index into this.annotations).
*/
_getAnnotationGroup: function(entity) {
var annotationGroup = {
serviceUnit: 'units',
environment: 'annotations'
}[entity.name];
if (!annotationGroup) {
annotationGroup = entity.name + 's';
}
return annotationGroup;
},
/**
* Update annotations for a given entity. This performs a merge of existing
* annotations with any new data.
*
* @method updateAnnotations
* @param {String} entityName to update.
* @param {Object} annotations key/value map.
* @return {Object} either result or error property.
*/
updateAnnotations: function(entityName, annotations) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var entity = this.db.resolveModelByName(entityName);
var existing;
if (!entity) {
return {error: 'Unable to resolve entity: ' + entityName};
}
existing = models.getAnnotations(entity);
if (existing === undefined) {
existing = {};
}
models.setAnnotations(entity, annotations, true);
// Arrange delta stream updates.
var annotationGroup = this._getAnnotationGroup(entity);
this.annotations[annotationGroup][entityName] = entity;
return {result: true};
},
/**
* getAnnotations from an object. This uses standard name resolution (see
* db.resolveModelByName) to determine which object to return annotations
* for.
*
* @method getAnnotations
* @param {String} entityName to get annotations for.
* @return {Object} annotations as key/value map.
*/
getAnnotations: function(entityName) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var entity = this.db.resolveModelByName(entityName);
if (!entity) {
return {error: 'Unable to resolve entity: ' + entityName};
}
return {result: models.getAnnotations(entity)};
},
/**
* Remove annotations (optional by key) from an entity.
*
* @method removeAnnotations
* @param {String} entityName to remove annotations from.
* @param {Array} keys (optional) array of {String} keys to remove. If this
* is falsey all annotations are removed.
* @return {undefined} side effects only.
*/
removeAnnotations: function(entityName, keys) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var entity = this.db.resolveModelByName(entityName);
var annotations;
if (!entity) {
return {error: 'Unable to resolve entity: ' + entityName};
}
annotations = models.getAnnotations(entity);
if (annotations === undefined) {
annotations = {};
}
if (keys) {
Y.each(keys, function(k) {
if (Y.Object.owns(annotations, k)) {
delete annotations[k];
}
});
} else {
annotations = {};
}
// Apply merged annotations.
models.setAnnotations(entity, annotations);
// Arrange delta stream updates.
var annotationGroup = this._getAnnotationGroup(entity);
this.annotations[annotationGroup][entityName] = entity;
return {result: true};
},
/**
Sets the configuration settings on the supplied service to the supplied
config object while leaving the settings untouched if they are not in the
supplied config.
@method setConfig
@param {String} serviceName the service id.
@param {Object} config properties to set.
*/
setConfig: function(serviceName, config) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var service = this.db.services.getById(serviceName);
if (!service) {
return {error: 'Service "' + serviceName + '" does not exist.'};
}
var existing = service.get('config');
if (!existing) {
existing = {};
}
if (!config) {
config = {};
}
// Merge new config in.
existing = Y.mix(existing, config, true, undefined, 0, true);
//TODO: validate the config.
// Reassign the attr.
service.set('config', existing);
// The callback indicates done, we can pass anything back.
this.changes.services[service.get('id')] = [service, true];
return {result: existing};
},
/**
Sets the constraints on a service to restrict the type of machine to be
used for the service.
@method setConstraints
@param {String} serviceName the service id.
@param {Object | Array} data either an array of strings "foo=bar" or an
object {foo: 'bar'}.
*/
setConstraints: function(serviceName, data) {
var constraints = {};
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var service = this.db.services.getById(serviceName);
if (!service) {
return {error: 'Service "' + serviceName + '" does not exist.'};
}
var existing = service.get('constraints');
if (!existing) {
existing = {};
}
if (Y.Lang.isArray(data)) {
Y.Array.each(data, function(i) {
var kv = i.split('=');
constraints[kv[0]] = kv[1];
});
} else if (data) {
constraints = data;
}
// Merge new constraints in.
existing = Y.mix(existing, constraints, true, undefined, 0, true);
// TODO: Validate the constraints.
// Reassign the attr.
service.set('constraints', existing);
this.changes.services[service.get('id')] = [service, true];
return {result: true};
},
/**
* Mark a unit or a unit relation as resolved. In the fakebackend
* this validates arguments but doesn't take any real action.
*
* @method resolved
* @param {String} unitName tp resp;ve.
* @param {String} (optional) relationName to resolve for unit.
* @return {Object} with result or error.
*/
resolved: function(unitName, relationName) {
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
var serviceName = unitName.split('/', 1)[0];
var service = this.db.services.getById(serviceName);
var unit;
if (service) {
unit = service.get('units').getById(unitName);
}
if (!service || !unit) {
return {error: 'Unit "' + unitName + '" does not exist.'};
}
if (relationName) {
var relation = this.db.relations.get_relations_for_service(
service).filter(function(rel) {
return (rel.endpoints[0].name === relationName ||
rel.endpoints[1].name === relationName);
});
if (relation.length === 0) {
return {error: 'Relation ' + relationName +
' not found for ' + unitName};
}
}
// No hooks are run in the fakebackend so at this time resolve does
// nothing. We could make it clear error status but that isn't what
// resolved actually does. We could additionally push the unit into
// the change set but no change currently takes place.
return {result: true};
},
/**
* Utility to promise to load a charm for serviceData.
* @method _promiseCharmForService
* @param {Object} serviceData to load charm for. seviceData is the
* imported service attributes, so .charm should be the charm
* url.
* @return {Promise} resolving with [charm model, serviceData].
*/
_promiseCharmForService: function(serviceData) {
var self = this,
charmId = serviceData.charm;
return Y.Promise(function(resolve, reject) {
self._loadCharm(charmId, {
/**
* Callback to return resolved charm
* as associated serviceData (so it can
* be updated if version changed).
*
* @method success
*/
success: function(charm) {
resolve([charm, serviceData]);
},
failure: reject
});
});
},
/**
* Export environment state
*
* @method exportEnvironment
* @return {String} JSON description of env data.
*/
exportEnvironment: function() {
var serviceList = this.db.services,
relationList = this.db.relations,
result = {meta: {
exportFormat: 1.0
},
services: [], relations: []},
blackLists = {
service: ['id', 'aggregated_status', 'clientId', 'initialized',
'constraintsStr', 'destroyed', 'pending'],
relation: ['id', 'relation_id', 'clientId', 'initialized',
'destroyed', 'pending']
};
if (!this.get('authenticated')) {
return UNAUTHENTICATED_ERROR;
}
serviceList.each(function(s) {
var serviceData = s.getAttrs();
if (serviceData.pending === true) {
return;
}
Y.each(blackLists.service, function(key) {
if (key in serviceData) {
delete serviceData[key];
}
// Add in initial unit count.
var units = s.get('units');
serviceData.unit_count = units.size() || 1;
});
result.services.push(serviceData);
});
relationList.each(function(r) {
var relationData = r.getAttrs();
if (relationData.pending === true) {
return;
}
Y.each(blackLists.relation, function(key) {
if (key in relationData) {
delete relationData[key];
}
});
result.relations.push(relationData);
});
return {result: result};
},
/**
Single atomic, non-mutating parse of a bundle
followed by things like id assignment, this
returns a complex data structure which is used
by importDeployer to enact the deploy.
@method ingestDeployer
*/
ingestDeployer: function(data, options) {
if (!data) {return;}
options = options || {};
var db = this.db;
var rewriteIds = options.rewriteIds || false;
var targetBundle = options.targetBundle;
var useGhost = options.useGhost;
if (useGhost === undefined) {
useGhost = true;
}
if (!targetBundle && Object.keys(data).length > 1) {
throw new Error('Import target ambigious, aborting.');
}
// Builds out a object with inherited properties.
var source = targetBundle && data[targetBundle] ||
data[Object.keys(data)[0]];
var ancestors = [];
var seen = [];
/**
Helper to build out an inheritence chain
@method setupinheritance
@param {Object} base object currently being inspected.
@param {Array} baseList chain of ancestors to later inherit.
@param {Object} bundleData import data used to resolve ancestors.
@param {Array} seen list used to track objects already in inheritence
chain. @return {Array} of all inherited objects ordered from most base
to most specialized.
*/
function setupInheritance(base, baseList, bundleData, seen) {
// local alias for internal function.
var sourceData = bundleData;
var seenList = seen;
baseList.unshift(base);
// Normalize to array when present.
if (!base.inherits) { return; }
if (base.inherits && !Y.Lang.isArray(base.inherits)) {
base.inherits = [base.inherits];
}
base.inherits.forEach(function(ancestor) {
var baseDeploy = sourceData[ancestor];
if (baseDeploy === undefined) {
throw new Error('Unable to resolve bundle inheritence.');
}
if (seenList.indexOf(ancestor) === -1) {
seenList.push(ancestor);
setupInheritance(baseDeploy, baseList, bundleData, seenList);
}
});
}
setupInheritance(source, ancestors, data, seen);
// Source now merges it all.
source = {};
ancestors.forEach(function(ancestor) {
// Mix Merge and overwrite in order of inheritance
Y.mix(source, ancestor, true, undefined, 0, true);
});
// Create an id mapping. This will track the ids of objects
// read from data as they are mapped into db. When options
// rewriteIds is true this is required for services, but some
// types of object ids ('relations' for example) can always
// be rewritten but depend on the use of the proper ids.
// By building this mapping now we can detect collisions
// prior to mutating the database.
var serviceIdMap = {};
/**
Helper to generate the next valid service id.
@method nextServiceId
@return {String} next service id to use.
*/
function nextServiceId(modellist, id) {
var existing = modellist.getById(id);
var count = 0;
var target;
while (existing) {
count += 1;
target = id + '-' + count;
existing = modellist.getById(target);
}
return target;
}
Object.keys(source.services).forEach(function(serviceName) {
var current = source.services[serviceName];
var existing = db.services.getById(serviceName);
var targetId = serviceName;
if (existing) {
if (!rewriteIds) {
throw new Error(serviceName +
' is already present in the database.');
}
targetId = nextServiceId(db.services, serviceName);
current.id = targetId;
}
serviceIdMap[serviceName] = targetId;
});
return {
services: source.services,
relations: source.relations
};
},
/**
Import Deployer from YAML files
@method importDeployer
@param {String} YAMLData YAML string data to import.
@param {String} [name] Name of bundle within deployer file to import.
@param {Function} callback Triggered on completion of the import.
@return {undefined} Callback only.
*/
importDeployer: function(YAMLData, name, callback) {
var self = this;
if (!this.get('authenticated')) {
return callback(UNAUTHENTICATED_ERROR);
}
var data;
if (typeof YAMLData === 'string') {
try {
data = jsyaml.safeLoad(YAMLData);
} catch (e) {
console.log('error parsing deployer bundle');
return callback(VALUE_ERROR);
}
} else {
// Allow passing in Objects directly to ease testing.
data = YAMLData;
}
// XXX: The proper API doesn't allow options for the level
// of control that ingest allows. This should be addressed
// in the future.
var options = {};
if (name) {
options.targetBundle = name;
}
var ingestedData = this.ingestDeployer(data, options);
var servicePromises = [];
Y.each(ingestedData.services, function(serviceData) {
// Map the argument name from the deployer format
// name for unit count.
if (!serviceData.unitCount) {
serviceData.unitCount = serviceData.num_units || 1;
}
servicePromises.push(
self.promiseDeploy(serviceData.charm, serviceData));
});
self._deploymentId += 1;
var deployStatus = {
DeploymentId: self._deploymentId,
Status: 'started',
Timestamp: Date.now()
};
self._importChanges.push(deployStatus);
// Keep the list limited to the last 5
if (self._importChanges.length > 5) {
self._importChanges = self._importChanges.slice(-5);
}
Y.batch.apply(this, servicePromises)
.then(function(serviceDeployResult) {
serviceDeployResult.forEach(function(sdr) {
// Update export elements that 'deploy'
// doesn't handle
var service = sdr.service;
var serviceId = service.get('id');
var serviceData = ingestedData.services[serviceId];
// Force the annotation update (deploy doesn't handle this).
var annotiations = serviceData.annotations;
if (annotiations) {
service.set('annotations', annotiations);
}
// Expose
if (serviceData.exposed) {
self.expose(serviceId);
}
self.changes.services[sdr.service.get('id')] = [
sdr.service, true];
});
ingestedData.relations.forEach(function(relationData) {
var relResult = self.addRelation(
relationData[0], relationData[1], true);
self.changes.relations[relResult.relation.get('id')] = [
relResult.relation, true];
});
})
.then(function() {
deployStatus.Status = 'completed';
callback({DeploymentId: self._deploymentId});
}, function(err) {
deployStatus.Status = 'failed';
callback({Error: err.toString()});
});
},
/**
Promise the result of an importDeployer call. This method
exists to aid tests which use the import system to quickly
generate fixtures.
@method promiseDeploy
@param {String} YAMLData YAML data to import.
@param {String} [name] Bundle name to import.
@return {Promise} After the import is run.
*/
promiseImport: function(YAMLData, name) {
var self = this;
return new Y.Promise(function(resolve) {
self.importDeployer(YAMLData, name, resolve);
});
},
/**
Query the deployer import code for global status of the last 5 imports. We
don't currently queue but a real impl would need to always include every
pending import regardless of queue length
@method statusDeployer
@param {Function} callback Triggered with completion information.
@return {undefined} Callback only.
*/
statusDeployer: function(callback) {
if (!this.get('authenticated')) {
return callback(UNAUTHENTICATED_ERROR);
}
callback({LastChanges: this._importChanges});
}
});
Y.namespace('juju.environments').FakeBackend = FakeBackend;
}, '0.1.0', {
requires: [
'base',
'js-yaml',
'juju-models',
'promise'
]
});
|