download button for ssh commands
[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.downloadSSH = function(model) {\r
301     var 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 htmlView = new HTMLView({html: '<pre style="overflow: auto; word-wrap: normal; white-space: pre; word-wrap: normal;">' + sshCommands + '</pre>'});\r
313     XOSTenantApp.tenantSSHCommandsInterior.show(htmlView);\r
314 \r
315     $("#tenant-ssh-commands-dialog").dialog({\r
316        autoOpen: false,
317        modal: true,
318        width: 640,
319        buttons : {
320             "Download": function() {
321                 var dlLink = document.createElement('a');
322                 dlLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(sshCommands));
323                 dlLink.setAttribute('download', 'sshcommands.txt');
324                 dlLink.click();
325
326                 //window.open('data:text/text,' + encodeURIComponent(sshCommands));
327             },
328             "Close" : function() {
329               $(this).dialog("close");
330             },
331           }
332         });
333     $("#tenant-ssh-commands-dialog").dialog("open");\r
334 };\r
335 \r
336 XOSTenantApp.deleteSlice = function(model) {\r
337     var app=this;\r
338     app.deleteDialog(model, function() { console.log("afterDelete"); app.viewSlice(undefined); });\r
339 };\r
340 \r
341 XOSTenantApp.viewSlice = function(model) {\r
342     if (XOSTenantApp.dirty) {\r
343         if (!confirm("The current sliver has unsaved data -- view new sliver anyway ?")) {\r
344             $("#tenantSliceSelector select").val(XOSTenantApp.currentSlice.id);\r
345             return;\r
346         }\r
347     }\r
348 \r
349     XOSTenantApp.setDirty(false);\r
350 \r
351     if (!model && xos.slicesPlus.models.length > 0) {\r
352         model = xos.slicesPlus.models[0];\r
353     }\r
354 \r
355     if (model) {\r
356         sliceSelector = new XOSTenantApp.tenantSliceSelectorView({collection: xos.slicesPlus,\r
357                                                                   selectedID: model ? model.id : null,\r
358                                                                  } );\r
359         XOSTenantApp.sliceSelector = sliceSelector;\r
360         XOSTenantApp.tenantSliceSelector.show(sliceSelector);\r
361 \r
362         tenantSummary = new XOSTenantApp.tenantSummaryView({model: model,\r
363                                                             choices: {mount_data_sets: make_choices(xos.tenant().public_volume_names, null),\r
364                                                                       serviceClass: make_choices(xos.tenant().blessed_service_class_names, xos.tenant().blessed_service_classes),\r
365                                                                       default_image: make_choices(xos.tenant().blessed_image_names, xos.tenant().blessed_images),\r
366                                                                       default_flavor: make_choices(xos.tenant().blessed_flavor_names, xos.tenant().blessed_flavors),},\r
367                                                            });\r
368         XOSTenantApp.tenantSummary.show(tenantSummary);\r
369 \r
370         tenantSites = new XOSTenantSiteCollection();\r
371         tenantSites.getFromSlice(model);\r
372         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
373         model.usersOrig = model.attributes.users;   /* save an immutable copy that we'll use for username lookups */\r
374         model.user_namesOrig = model.attributes.user_names;\r
375         model.tenantSiteCollection = tenantSites;\r
376         XOSTenantApp.tenantSites = tenantSites;\r
377 \r
378         tenantSiteList = new XOSTenantApp.tenantSiteListView({collection: tenantSites });\r
379         XOSTenantApp.tenantSiteList.show(tenantSiteList);\r
380         // on xos.slicePlus.sort, need to update xostenantapp.tenantSites\r
381 \r
382         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { app: XOSTenantApp,\r
383                                                                     linkedView: tenantSummary } ) );\r
384 \r
385         XOSTenantApp.currentSlice = model;\r
386     } else {\r
387         XOSTenantApp.tenantSliceSelector.show(new HTMLView({html: ""}));\r
388         XOSTenantApp.tenantSummary.show(new HTMLView({html: "You have no slices"}));\r
389         XOSTenantApp.tenantSiteList.show(new HTMLView({html: ""}));\r
390         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { template: "#xos-tenant-buttons-noslice-template",\r
391                                                                     app: XOSTenantApp,\r
392                                                                     linkedView: tenantSummary } ) );\r
393     }\r
394 };\r
395 \r
396 XOSTenantApp.sanityCheck = function() {\r
397     errors = [];\r
398     if (xos.tenant().blessed_service_classes.length == 0) {\r
399         errors.push("no blessed service classes");\r
400     }\r
401     if (xos.tenant().blessed_flavors.length == 0) {\r
402         errors.push("no blessed flavors");\r
403     }\r
404     if (xos.tenant().blessed_images.length == 0) {\r
405         errors.push("no blessed images");\r
406     }\r
407     if (xos.tenant().blessed_sites.length == 0) {\r
408         errors.push("no blessed sites");\r
409     }\r
410     if (xos.tenant().current_user_site_id == null) {\r
411         errors.push("current user does not have a site");\r
412     }\r
413 \r
414     if (errors.length > 0) {\r
415          $("#tenantSummary").html("Tenant view sanity check failed<br>" + errors.join("<br>"));\r
416          return false;\r
417     }\r
418 \r
419     return true;\r
420 }\r
421 \r
422 XOSTenantApp.collectionLoadChange = function() {\r
423     stats = xos.getCollectionStatus();\r
424 \r
425     if (!XOSTenantApp.navigationStarted) {\r
426         if (stats["isLoaded"] + stats["failedLoad"] >= stats["startedLoad"]) {\r
427             if (XOSTenantApp.sanityCheck()) {\r
428                 XOSTenantApp.viewSlice(undefined);\r
429             }\r
430         } else {\r
431             $("#tenantSummary").html("<h3>Loading...</h3><div id='xos-startup-progress'></div>");\r
432             $("#xos-startup-progress").progressbar({value: stats["completedLoad"], max: stats["startedLoad"]});\r
433         }\r
434     }\r
435 };\r
436 \r
437 XOSTenantApp.on("start", function() {\r
438      XOSTenantApp.buildViews();
439
440      // fire it once to initially show the progress bar
441      XOSTenantApp.collectionLoadChange();
442
443      // fire it each time the collection load status is updated
444      Backbone.on("xoslib:collectionLoadChange", XOSTenantApp.collectionLoadChange);
445 });
446
447 $(document).ready(function(){
448     XOSTenantApp.start();
449 });
450