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