warning for Service Level as well
[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: {"serviceClass": "Existing slivers will be re-instantiated if changed",\r
141                                                            "default_image": "Existing slivers will be re-instantiated if changed",\r
142                                                            "default_flavor": "Existing slivers will be re-instantiated if changed"},\r
143 \r
144                                                 onShow: function() {\r
145                                                     // the slice selector is in a different table, so make every label cell the maximal width\r
146                                                     make_same_width("#xos-tenant-view-panel", ".xos-label-cell");\r
147                                                 },\r
148                                                 });\r
149 \r
150      XOSTenantApp.tenantSummaryView = tenantSummaryClass;\r
151 \r
152      tenantAddClass = XOSDetailView.extend({template: "#xos-detail-template",\r
153                                                 app: XOSTenantApp,\r
154                                                 detailFields: ["name", "description"]});\r
155 \r
156      XOSTenantApp.tenantAddView = tenantAddClass;\r
157 \r
158      tenantSiteItemClass = XOSItemView.extend({template: "#xos-listitem-template",\r
159                                                app: XOSTenantApp});\r
160 \r
161      XOSTenantApp.tenantSiteItemView = tenantSiteItemClass;\r
162 \r
163      tenantSiteListClass = XOSDataTableView.extend({template: "#xos-list-template",\r
164                                                app: XOSTenantApp,\r
165                                                childView: tenantSiteItemClass,\r
166                                                collection: XOSTenantApp.tenantSites,\r
167                                                title: "sites",\r
168                                                inputType: {allocated: "spinner"},\r
169                                                noDeleteColumn: true,\r
170                                                disablePaginate: true,\r
171                                                disableFilter: true,\r
172                                                fieldDisplayNames: {"name": "Site"},\r
173                                                });\r
174 \r
175      XOSTenantApp.tenantSiteListView = tenantSiteListClass;\r
176 \r
177      XOSTenantApp.tenantSliceSelectorView = SliceSelectorView.extend( {\r
178          sliceChanged: function(id) {\r
179              XOSTenantApp.navToSlice(id);\r
180          },\r
181      });\r
182 \r
183      xos.sites.fetch();\r
184      xos.slicesPlus.fetch();\r
185      xos.tenantview.fetch();\r
186 };\r
187 \r
188 make_choices = function(list_of_names, list_of_values) {\r
189     result = [];\r
190     if (!list_of_values) {\r
191         for (index in list_of_names) {\r
192             displayName = list_of_names[index];\r
193             result.push( [displayName, displayName] );\r
194         }\r
195     } else {\r
196         for (index in list_of_names) {\r
197             displayName = list_of_names[index];\r
198             id = list_of_values[index];\r
199             result.push( [displayName, id] );\r
200         }\r
201     }\r
202     return result;\r
203 };\r
204 \r
205 XOSTenantApp.navToSlice = function(id) {\r
206     XOSTenantApp.viewSlice(xos.slicesPlus.get(id));\r
207 };\r
208 \r
209 XOSTenantApp.adjustCollectionField = function(collectionName, id, fieldName, amount) {\r
210     model = XOSTenantApp[collectionName].get(id);\r
211     model.set(fieldName, Math.max(model.get(fieldName) + amount, 0));\r
212     XOSTenantApp.setDirty(true);\r
213 };\r
214 \r
215 XOSTenantApp.addSlice = function() {\r
216     var app=this;\r
217 \r
218     if (!xos.tenant().current_user_can_create_slice) {\r
219         window.alert("You do not have sufficient rights to create a slice on your site");\r
220         return;\r
221     }\r
222 \r
223     model = new xos.slicesPlus.model({site: xos.tenant().current_user_site_id,\r
224                                       name: xos.tenant().current_user_login_base + "_",\r
225                                       creator: xos.tenant().current_user_id});\r
226     console.log(model);\r
227     var detailView = new XOSTenantApp.tenantAddView({model: model,\r
228                                                      collection: xos.slicesPlus,\r
229                                                      noSubmitButton: true,\r
230                                                     });\r
231     detailView.dialog = $("#tenant-addslice-dialog");\r
232     app.tenantAddSliceInterior.show(detailView);\r
233     $("#tenant-addslice-dialog").dialog({\r
234        autoOpen: false,
235        modal: true,
236        width: 640,
237        buttons : {
238             "Create Slice" : function() {
239               var addDialog = this;
240               console.log("SAVE!!!");
241               detailView.synchronous = true;
242               detailView.afterSave = function() { $(addDialog).dialog("close"); XOSTenantApp.navToSlice(detailView.model.id); }
243               detailView.save();
244             },
245             "Cancel" : function() {
246               $(this).dialog("close");
247             }
248           }
249         });
250     $("#tenant-addslice-dialog").dialog("open");\r
251 };\r
252 \r
253 XOSTenantApp.editUsers = function(model) {\r
254     var app=this;\r
255     var detailView = new XOSEditUsersView({model: model, collection: xos.slicesPlus});\r
256     detailView.dialog = $("#tenant-edit-users-dialog");\r
257     app.tenantEditUsersInterior.show(detailView);\r
258     $("#tenant-edit-users-dialog").dialog({\r
259        autoOpen: false,
260        modal: true,
261        width: 640,
262        buttons : {
263             "Ok" : function() {
264               var editDialog = this;
265               user_ids = all_options($("#tenant-edit-users-dialog").find(".select-picker-to"));
266               user_ids = user_ids.map( function(x) { return parseInt(x,10); } );
267               if (!array_same_elements(user_ids, model.usersBuffer)) {
268                   XOSTenantApp.setDirty(true);
269               }
270               model.usersBuffer = user_ids;
271               $(editDialog).dialog("close");
272             },
273             "Cancel" : function() {
274               $(this).dialog("close");
275             }
276           }
277         });
278     $("#tenant-edit-users-dialog").dialog("open");\r
279 };\r
280 \r
281 XOSTenantApp.downloadSSHOld = function(model) {\r
282     sshCommands = "";\r
283     for (index in model.attributes.sliceInfo.sshCommands) {\r
284          sshCommand = model.attributes.sliceInfo.sshCommands[index];\r
285          sshCommands = sshCommands + sshCommand + "\n";\r
286     }\r
287 \r
288     if (sshCommands.length == 0) {\r
289          alert("this slice has no instantiated slivers yet");\r
290          return;\r
291     }\r
292 \r
293     var myWindow = window.open("", "ssh_command_list",""); // "width=640, height=480");\r
294     myWindow.document.write("<html><head><title>SSH Commands</title></head><body><pre>" + sshCommands + "</pre></body></html>");\r
295     myWindow.document.close();\r
296 };\r
297 \r
298 XOSTenantApp.downloadSSH = function(model) {\r
299     sshCommands = "";\r
300     for (index in model.attributes.sliceInfo.sshCommands) {\r
301          sshCommand = model.attributes.sliceInfo.sshCommands[index];\r
302          sshCommands = sshCommands + sshCommand + "\n";\r
303     }\r
304 \r
305     if (sshCommands.length == 0) {\r
306          alert("this slice has no instantiated slivers yet");\r
307          return;\r
308     }\r
309 \r
310     var htmlView = new HTMLView({html: '<pre style="overflow: auto; word-wrap: normal; white-space: pre; word-wrap: normal;">' + sshCommands + '</pre>'});\r
311     XOSTenantApp.tenantSSHCommandsInterior.show(htmlView);\r
312 \r
313     $("#tenant-ssh-commands-dialog").dialog({\r
314        autoOpen: false,
315        modal: true,
316        width: 640,
317        buttons : {
318             "Ok" : function() {
319               $(this).dialog("close");
320             },
321           }
322         });
323     $("#tenant-ssh-commands-dialog").dialog("open");\r
324 };\r
325 \r
326 XOSTenantApp.deleteSlice = function(model) {\r
327     var app=this;\r
328     app.deleteDialog(model, function() { console.log("afterDelete"); app.viewSlice(undefined); });\r
329 };\r
330 \r
331 XOSTenantApp.viewSlice = function(model) {\r
332     if (XOSTenantApp.dirty) {\r
333         if (!confirm("The current sliver has unsaved data -- view new sliver anyway ?")) {\r
334             $("#tenantSliceSelector select").val(XOSTenantApp.currentSlice.id);\r
335             return;\r
336         }\r
337     }\r
338 \r
339     XOSTenantApp.setDirty(false);\r
340 \r
341     if (!model && xos.slicesPlus.models.length > 0) {\r
342         model = xos.slicesPlus.models[0];\r
343     }\r
344 \r
345     if (model) {\r
346         sliceSelector = new XOSTenantApp.tenantSliceSelectorView({collection: xos.slicesPlus,\r
347                                                                   selectedID: model ? model.id : null,\r
348                                                                  } );\r
349         XOSTenantApp.sliceSelector = sliceSelector;\r
350         XOSTenantApp.tenantSliceSelector.show(sliceSelector);\r
351 \r
352         tenantSummary = new XOSTenantApp.tenantSummaryView({model: model,\r
353                                                             choices: {mount_data_sets: make_choices(xos.tenant().public_volume_names, null),\r
354                                                                       serviceClass: make_choices(xos.tenant().blessed_service_class_names, xos.tenant().blessed_service_classes),\r
355                                                                       default_image: make_choices(xos.tenant().blessed_image_names, xos.tenant().blessed_images),\r
356                                                                       default_flavor: make_choices(xos.tenant().blessed_flavor_names, xos.tenant().blessed_flavors),},\r
357                                                            });\r
358         XOSTenantApp.tenantSummary.show(tenantSummary);\r
359 \r
360         tenantSites = new XOSTenantSiteCollection();\r
361         tenantSites.getFromSlice(model);\r
362         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
363         model.usersOrig = model.attributes.users;   /* save an immutable copy that we'll use for username lookups */\r
364         model.user_namesOrig = model.attributes.user_names;\r
365         model.tenantSiteCollection = tenantSites;\r
366         XOSTenantApp.tenantSites = tenantSites;\r
367 \r
368         tenantSiteList = new XOSTenantApp.tenantSiteListView({collection: tenantSites });\r
369         XOSTenantApp.tenantSiteList.show(tenantSiteList);\r
370         // on xos.slicePlus.sort, need to update xostenantapp.tenantSites\r
371 \r
372         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { app: XOSTenantApp,\r
373                                                                     linkedView: tenantSummary } ) );\r
374 \r
375         XOSTenantApp.currentSlice = model;\r
376     } else {\r
377         XOSTenantApp.tenantSliceSelector.show(new HTMLView({html: ""}));\r
378         XOSTenantApp.tenantSummary.show(new HTMLView({html: "You have no slices"}));\r
379         XOSTenantApp.tenantSiteList.show(new HTMLView({html: ""}));\r
380         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { template: "#xos-tenant-buttons-noslice-template",\r
381                                                                     app: XOSTenantApp,\r
382                                                                     linkedView: tenantSummary } ) );\r
383     }\r
384 };\r
385 \r
386 XOSTenantApp.sanityCheck = function() {\r
387     errors = [];\r
388     if (xos.tenant().blessed_service_classes.length == 0) {\r
389         errors.push("no blessed service classes");\r
390     }\r
391     if (xos.tenant().blessed_flavors.length == 0) {\r
392         errors.push("no blessed flavors");\r
393     }\r
394     if (xos.tenant().blessed_images.length == 0) {\r
395         errors.push("no blessed images");\r
396     }\r
397     if (xos.tenant().blessed_sites.length == 0) {\r
398         errors.push("no blessed sites");\r
399     }\r
400     if (xos.tenant().current_user_site_id == null) {\r
401         errors.push("current user does not have a site");\r
402     }\r
403 \r
404     if (errors.length > 0) {\r
405          $("#tenantSummary").html("Tenant view sanity check failed<br>" + errors.join("<br>"));\r
406          return false;\r
407     }\r
408 \r
409     return true;\r
410 }\r
411 \r
412 XOSTenantApp.collectionLoadChange = function() {\r
413     stats = xos.getCollectionStatus();\r
414 \r
415     if (!XOSTenantApp.navigationStarted) {\r
416         if (stats["isLoaded"] + stats["failedLoad"] >= stats["startedLoad"]) {\r
417             if (XOSTenantApp.sanityCheck()) {\r
418                 XOSTenantApp.viewSlice(undefined);\r
419             }\r
420         } else {\r
421             $("#tenantSummary").html("<h3>Loading...</h3><div id='xos-startup-progress'></div>");\r
422             $("#xos-startup-progress").progressbar({value: stats["completedLoad"], max: stats["startedLoad"]});\r
423         }\r
424     }\r
425 };\r
426 \r
427 XOSTenantApp.on("start", function() {\r
428      XOSTenantApp.buildViews();
429
430      // fire it once to initially show the progress bar
431      XOSTenantApp.collectionLoadChange();
432
433      // fire it each time the collection load status is updated
434      Backbone.on("xoslib:collectionLoadChange", XOSTenantApp.collectionLoadChange);
435 });
436
437 $(document).ready(function(){
438     XOSTenantApp.start();
439 });
440