display count of ready slivers in tenant view
[plstackapi.git] / planetstack / core / xoslib / static / js / xosTenant.js
1 XOSTenantSite = XOSModel.extend( {
2     listFields: ["name", "allocated"],
3     modelName: "tenantSite",
4     collectionName: "tenantSites"
5 });
6
7 XOSTenantSiteCollection = XOSCollection.extend( {
8     listFields: ["name", "allocated", "ready"],
9     modelName: "tenantSite",
10     collectionName: "tenantSites",
11
12     getFromSlice: function(slice) {
13         var tenantSites = [];
14         var id = 0;
15         for (siteName in slice.attributes.site_allocation) {
16             allocated = slice.attributes.site_allocation[siteName];
17             ready = slice.attributes.site_ready[siteName] || 0;
18             tenantSites.push(new XOSTenantSite( { name: siteName, allocated: allocated, ready: ready, id: id} ));
19             id = id + 1;
20         }
21         for (index in xos.tenantview.models[0].attributes.blessed_site_names) {
22             siteName = xos.tenantview.models[0].attributes.blessed_site_names[index];
23             if (! (siteName in slice.attributes.site_allocation)) {
24                 tenantSites.push(new XOSTenantSite( { name: siteName, allocated: 0, ready: 0, id: id} ));
25                 id = id + 1;
26             }
27         }
28         this.set(tenantSites);
29
30         var that=this;
31         this.listenTo(slice, 'change', function() { that.getReadyFromSlice(slice); })
32     },
33
34     getReadyFromSlice: function(slice) {
35         for (siteName in slice.attributes.site_ready) {
36             ready = slice.attributes.site_ready[siteName];
37             for (index in this.models) {
38                 tenantSite = this.models[index];
39                 if (tenantSite.attributes.name == siteName) {
40                     tenantSite.set("ready", ready);
41                 }
42             }
43         }
44     },
45
46     putToSlice: function(slice) {
47         slice.attributes.site_allocation = {};
48         for (index in this.models) {
49             var model = this.models[index];
50             slice.attributes.site_allocation[ model.attributes.name ] = model.attributes.allocated;
51         }
52     },
53 });
54
55 XOSEditUsersView = Marionette.ItemView.extend({
56             template: "#tenant-edit-users",
57             viewInitializers: [],
58
59             onShow: function() {
60                 _.each(this.viewInitializers, function(initializer) {
61                     initializer();
62                 });
63             },
64
65             templateHelpers: function() { return { detailView: this, model: this.model }; },
66
67             });
68
69 XOSTenantSummaryView = XOSDetailView.extend({
70             events: {"change": "onChange"},
71
72             onChange: function(e) {
73                 XOSTenantApp.setDirty(true);
74             },
75
76             saveSuccess: function() {
77                 console.log("saveSuccess!");
78                 XOSTenantApp.setDirty(false);
79             },
80
81             });
82
83
84 XOSTenantButtonView = Marionette.ItemView.extend({
85             template: "#xos-tenant-buttons-template",
86
87             events: {"click button.btn-tenant-create": "createClicked",
88                      "click button.btn-tenant-delete": "deleteClicked",
89                      "click button.btn-tenant-add-user": "addUserClicked",
90                      "click button.btn-tenant-save": "saveClicked",
91                      "click button.btn-tenant-download-ssh": "downloadClicked",
92                      },
93
94             createClicked: function(e) {
95                      XOSTenantApp.addSlice();
96                      },
97
98             deleteClicked: function(e) {
99                      XOSTenantApp.deleteSlice(this.options.linkedView.model);
100                      },
101
102             addUserClicked: function(e) {
103                      XOSTenantApp.editUsers(this.options.linkedView.model);
104                      },
105
106             downloadClicked: function(e) {
107                      XOSTenantApp.downloadSSH(this.options.linkedView.model);
108                      },
109
110             saveClicked: function(e) {
111                      model = this.options.linkedView.model;
112                      model.tenantSiteCollection.putToSlice(model);
113                      model.attributes.users = model.usersBuffer;
114
115                      e.preventDefault();
116                      this.options.linkedView.save();
117                      //this.options.linkedView.submitContinueClicked.call(this.options.linkedView, e);
118                      //XOSTenantApp.setDirty(false);
119                      },
120             });
121
122 XOSTenantApp = new XOSApplication({
123     logTableId: "#logTable",
124     statusMsgId: "#statusMsg",
125     hideTabsByDefault: true,
126     dirty: false,
127     varName: "XOSTenantApp",
128 });
129
130 XOSTenantApp.addRegions({
131     tenantSliceSelector: "#tenantSliceSelector",
132     tenantSummary: "#tenantSummary",
133     tenantSiteList: "#tenantSiteList",
134     tenantButtons: "#tenantButtons",
135     tenantAddSliceInterior: "#tenant-addslice-interior",
136     tenantEditUsersInterior: "#tenant-edit-users-interior",
137     tenantSSHCommandsInterior: "#tenant-ssh-commands-interior",
138 });
139
140 XOSTenantApp.setDirty = function(dirty) {
141     XOSTenantApp.dirty = dirty;
142     if (dirty) {
143         $("button.btn-tenant-save").addClass("btn-success");
144     } else {
145         $("button.btn-tenant-save").removeClass("btn-success");
146     }
147 };
148
149 XOSTenantApp.buildViews = function() {
150      XOSTenantApp.tenantSites = new XOSTenantSiteCollection();\r
151 \r
152      tenantSummaryClass = XOSTenantSummaryView.extend({template: "#xos-detail-template",\r
153                                                 app: XOSTenantApp,\r
154                                                 detailFields: ["serviceClass", "default_image", "default_flavor", "network_ports"],\r
155                                                 fieldDisplayNames: {serviceClass: "Service Level", "default_flavor": "Flavor", "default_image": "Image", "mount_data_sets": "Data Sets"},\r
156                                                 helpText: {"serviceClass": "Existing slivers will be re-instantiated if changed",\r
157                                                            "default_image": "Existing slivers will be re-instantiated if changed",\r
158                                                            "default_flavor": "Existing slivers will be re-instantiated if changed"},\r
159 \r
160                                                 onShow: function() {\r
161                                                     // the slice selector is in a different table, so make every label cell the maximal width\r
162                                                     make_same_width("#xos-tenant-view-panel", ".xos-label-cell");\r
163                                                 },\r
164                                                 });\r
165 \r
166      XOSTenantApp.tenantSummaryView = tenantSummaryClass;\r
167 \r
168      tenantAddClass = XOSDetailView.extend({template: "#xos-detail-template",\r
169                                                 app: XOSTenantApp,\r
170                                                 detailFields: ["name", "description"]});\r
171 \r
172      XOSTenantApp.tenantAddView = tenantAddClass;\r
173 \r
174      tenantSiteItemClass = XOSItemView.extend({template: "#xos-listitem-template",\r
175                                                app: XOSTenantApp});\r
176 \r
177      XOSTenantApp.tenantSiteItemView = tenantSiteItemClass;\r
178 \r
179      tenantSiteListClass = XOSDataTableView.extend({template: "#xos-list-template",\r
180                                                app: XOSTenantApp,\r
181                                                childView: tenantSiteItemClass,\r
182                                                collection: XOSTenantApp.tenantSites,\r
183                                                title: "sites",\r
184                                                inputType: {allocated: "spinner"},\r
185                                                noDeleteColumn: true,\r
186                                                disablePaginate: true,\r
187                                                disableFilter: true,\r
188                                                fieldDisplayNames: {"name": "Site"},\r
189                                                });\r
190 \r
191      XOSTenantApp.tenantSiteListView = tenantSiteListClass;\r
192 \r
193      XOSTenantApp.tenantSliceSelectorView = SliceSelectorView.extend( {\r
194          sliceChanged: function(id) {\r
195              XOSTenantApp.navToSlice(id);\r
196          },\r
197          filter: function(slice) {\r
198              return slice.attributes.current_user_can_see;\r
199          },\r
200      });\r
201 \r
202      xos.sites.fetch();\r
203      xos.slicesPlus.fetch();\r
204      xos.tenantview.fetch();\r
205 };\r
206 \r
207 make_choices = function(list_of_names, list_of_values) {\r
208     result = [];\r
209     if (!list_of_values) {\r
210         for (index in list_of_names) {\r
211             displayName = list_of_names[index];\r
212             result.push( [displayName, displayName] );\r
213         }\r
214     } else {\r
215         for (index in list_of_names) {\r
216             displayName = list_of_names[index];\r
217             id = list_of_values[index];\r
218             result.push( [displayName, id] );\r
219         }\r
220     }\r
221     return result;\r
222 };\r
223 \r
224 XOSTenantApp.navToSlice = function(id) {\r
225     XOSTenantApp.viewSlice(xos.slicesPlus.get(id));\r
226 };\r
227 \r
228 XOSTenantApp.adjustCollectionField = function(collectionName, id, fieldName, amount) {\r
229     model = XOSTenantApp[collectionName].get(id);\r
230     model.set(fieldName, Math.max(model.get(fieldName) + amount, 0));\r
231     XOSTenantApp.setDirty(true);\r
232 };\r
233 \r
234 XOSTenantApp.addSlice = function() {\r
235     var app=this;\r
236 \r
237     if (!xos.tenant().current_user_can_create_slice) {\r
238         window.alert("You do not have sufficient rights to create a slice on your site");\r
239         return;\r
240     }\r
241 \r
242     model = new xos.slicesPlus.model({site: xos.tenant().current_user_site_id,\r
243                                       name: xos.tenant().current_user_login_base + "_",\r
244                                       creator: xos.tenant().current_user_id});\r
245     console.log(model);\r
246     var detailView = new XOSTenantApp.tenantAddView({model: model,\r
247                                                      collection: xos.slicesPlus,\r
248                                                      noSubmitButton: true,\r
249                                                     });\r
250     detailView.dialog = $("#tenant-addslice-dialog");\r
251     app.tenantAddSliceInterior.show(detailView);\r
252     $("#tenant-addslice-dialog").dialog({\r
253        autoOpen: false,
254        modal: true,
255        width: 640,
256        buttons : {
257             "Create Slice" : function() {
258               var addDialog = this;
259               console.log("SAVE!!!");
260               detailView.synchronous = true;
261               detailView.afterSave = function() { $(addDialog).dialog("close"); XOSTenantApp.navToSlice(detailView.model.id); }
262               detailView.save();
263             },
264             "Cancel" : function() {
265               $(this).dialog("close");
266             }
267           }
268         });
269     $("#tenant-addslice-dialog").dialog("open");\r
270 };\r
271 \r
272 XOSTenantApp.editUsers = function(model) {\r
273     var app=this;\r
274     var detailView = new XOSEditUsersView({model: model, collection: xos.slicesPlus});\r
275     detailView.dialog = $("#tenant-edit-users-dialog");\r
276     app.tenantEditUsersInterior.show(detailView);\r
277     $("#tenant-edit-users-dialog").dialog({\r
278        autoOpen: false,
279        modal: true,
280        width: 640,
281        buttons : {
282             "Ok" : function() {
283               var editDialog = this;
284               user_ids = all_options($("#tenant-edit-users-dialog").find(".select-picker-to"));
285               user_ids = user_ids.map( function(x) { return parseInt(x,10); } );
286               if (!array_same_elements(user_ids, model.usersBuffer)) {
287                   XOSTenantApp.setDirty(true);
288               }
289               model.usersBuffer = user_ids;
290               $(editDialog).dialog("close");
291             },
292             "Cancel" : function() {
293               $(this).dialog("close");
294             }
295           }
296         });
297     $("#tenant-edit-users-dialog").dialog("open");\r
298 };\r
299 \r
300 XOSTenantApp.downloadSSHOld = function(model) {\r
301     sshCommands = "";\r
302     for (index in model.attributes.sliceInfo.sshCommands) {\r
303          sshCommand = model.attributes.sliceInfo.sshCommands[index];\r
304          sshCommands = sshCommands + sshCommand + "\n";\r
305     }\r
306 \r
307     if (sshCommands.length == 0) {\r
308          alert("this slice has no instantiated slivers yet");\r
309          return;\r
310     }\r
311 \r
312     var myWindow = window.open("", "ssh_command_list",""); // "width=640, height=480");\r
313     myWindow.document.write("<html><head><title>SSH Commands</title></head><body><pre>" + sshCommands + "</pre></body></html>");\r
314     myWindow.document.close();\r
315 };\r
316 \r
317 XOSTenantApp.downloadSSH = function(model) {\r
318     sshCommands = "";\r
319     for (index in model.attributes.sliceInfo.sshCommands) {\r
320          sshCommand = model.attributes.sliceInfo.sshCommands[index];\r
321          sshCommands = sshCommands + sshCommand + "\n";\r
322     }\r
323 \r
324     if (sshCommands.length == 0) {\r
325          alert("this slice has no instantiated slivers yet");\r
326          return;\r
327     }\r
328 \r
329     var htmlView = new HTMLView({html: '<pre style="overflow: auto; word-wrap: normal; white-space: pre; word-wrap: normal;">' + sshCommands + '</pre>'});\r
330     XOSTenantApp.tenantSSHCommandsInterior.show(htmlView);\r
331 \r
332     $("#tenant-ssh-commands-dialog").dialog({\r
333        autoOpen: false,
334        modal: true,
335        width: 640,
336        buttons : {
337             "Ok" : function() {
338               $(this).dialog("close");
339             },
340           }
341         });
342     $("#tenant-ssh-commands-dialog").dialog("open");\r
343 };\r
344 \r
345 XOSTenantApp.deleteSlice = function(model) {\r
346     var app=this;\r
347     app.deleteDialog(model, function() { console.log("afterDelete"); app.viewSlice(undefined); });\r
348 };\r
349 \r
350 XOSTenantApp.viewSlice = function(model) {\r
351     if (XOSTenantApp.dirty) {\r
352         if (!confirm("The current sliver has unsaved data -- view new sliver anyway ?")) {\r
353             $("#tenantSliceSelector select").val(XOSTenantApp.currentSlice.id);\r
354             return;\r
355         }\r
356     }\r
357 \r
358     XOSTenantApp.setDirty(false);\r
359 \r
360     if (!model && xos.slicesPlus.models.length > 0) {\r
361         model = xos.slicesPlus.models[0];\r
362     }\r
363 \r
364     if (model) {\r
365         sliceSelector = new XOSTenantApp.tenantSliceSelectorView({collection: xos.slicesPlus,\r
366                                                                   selectedID: model ? model.id : null,\r
367                                                                  } );\r
368         XOSTenantApp.sliceSelector = sliceSelector;\r
369         XOSTenantApp.tenantSliceSelector.show(sliceSelector);\r
370 \r
371         tenantSummary = new XOSTenantApp.tenantSummaryView({model: model,\r
372                                                             choices: {mount_data_sets: make_choices(xos.tenant().public_volume_names, null),\r
373                                                                       serviceClass: make_choices(xos.tenant().blessed_service_class_names, xos.tenant().blessed_service_classes),\r
374                                                                       default_image: make_choices(xos.tenant().blessed_image_names, xos.tenant().blessed_images),\r
375                                                                       default_flavor: make_choices(xos.tenant().blessed_flavor_names, xos.tenant().blessed_flavors),},\r
376                                                            });\r
377         XOSTenantApp.tenantSummary.show(tenantSummary);\r
378 \r
379         tenantSites = new XOSTenantSiteCollection();\r
380         tenantSites.getFromSlice(model);\r
381         model.usersBuffer = model.attributes.users; /* save a copy of 'users' that we can edit. This prevents another view (developer) from overwriting our copy with a fetch from the server */\r
382         model.usersOrig = model.attributes.users;   /* save an immutable copy that we'll use for username lookups */\r
383         model.user_namesOrig = model.attributes.user_names;\r
384         model.tenantSiteCollection = tenantSites;\r
385         XOSTenantApp.tenantSites = tenantSites;\r
386 \r
387         tenantSiteList = new XOSTenantApp.tenantSiteListView({collection: tenantSites });\r
388         XOSTenantApp.tenantSiteList.show(tenantSiteList);\r
389         // on xos.slicePlus.sort, need to update xostenantapp.tenantSites\r
390 \r
391         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { app: XOSTenantApp,\r
392                                                                     linkedView: tenantSummary } ) );\r
393 \r
394         XOSTenantApp.currentSlice = model;\r
395     } else {\r
396         XOSTenantApp.tenantSliceSelector.show(new HTMLView({html: ""}));\r
397         XOSTenantApp.tenantSummary.show(new HTMLView({html: "You have no slices"}));\r
398         XOSTenantApp.tenantSiteList.show(new HTMLView({html: ""}));\r
399         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { template: "#xos-tenant-buttons-noslice-template",\r
400                                                                     app: XOSTenantApp,\r
401                                                                     linkedView: tenantSummary } ) );\r
402     }\r
403 };\r
404 \r
405 XOSTenantApp.sanityCheck = function() {\r
406     errors = [];\r
407     if (xos.tenant().blessed_service_classes.length == 0) {\r
408         errors.push("no blessed service classes");\r
409     }\r
410     if (xos.tenant().blessed_flavors.length == 0) {\r
411         errors.push("no blessed flavors");\r
412     }\r
413     if (xos.tenant().blessed_images.length == 0) {\r
414         errors.push("no blessed images");\r
415     }\r
416     if (xos.tenant().blessed_sites.length == 0) {\r
417         errors.push("no blessed sites");\r
418     }\r
419     if (xos.tenant().current_user_site_id == null) {\r
420         errors.push("current user does not have a site");\r
421     }\r
422 \r
423     if (errors.length > 0) {\r
424          $("#tenantSummary").html("Tenant view sanity check failed<br>" + errors.join("<br>"));\r
425          return false;\r
426     }\r
427 \r
428     return true;\r
429 }\r
430 \r
431 XOSTenantApp.collectionLoadChange = function() {\r
432     stats = xos.getCollectionStatus();\r
433 \r
434     if (!XOSTenantApp.navigationStarted) {\r
435         if (stats["isLoaded"] + stats["failedLoad"] >= stats["startedLoad"]) {\r
436             if (XOSTenantApp.sanityCheck()) {\r
437                 XOSTenantApp.viewSlice(undefined);\r
438             }\r
439         } else {\r
440             $("#tenantSummary").html("<h3>Loading...</h3><div id='xos-startup-progress'></div>");\r
441             $("#xos-startup-progress").progressbar({value: stats["completedLoad"], max: stats["startedLoad"]});\r
442         }\r
443     }\r
444 };\r
445 \r
446 XOSTenantApp.on("start", function() {\r
447      XOSTenantApp.buildViews();
448
449      // fire it once to initially show the progress bar
450      XOSTenantApp.collectionLoadChange();
451
452      // fire it each time the collection load status is updated
453      Backbone.on("xoslib:collectionLoadChange", XOSTenantApp.collectionLoadChange);
454 });
455
456 $(document).ready(function(){
457     XOSTenantApp.start();
458 });
459