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