display count of ready slivers in tenant view
[plstackapi.git] / planetstack / core / xoslib / static / js / xosTenant.js
index 5095505..79e093e 100644 (file)
@@ -5,29 +5,82 @@ XOSTenantSite = XOSModel.extend( {
 });
 
 XOSTenantSiteCollection = XOSCollection.extend( {
-    listFields: ["name", "allocated"],
+    listFields: ["name", "allocated", "ready"],
     modelName: "tenantSite",
     collectionName: "tenantSites",
 
-    updateFromSlice: function(slice) {
+    getFromSlice: function(slice) {
         var tenantSites = [];
         var id = 0;
         for (siteName in slice.attributes.site_allocation) {
             allocated = slice.attributes.site_allocation[siteName];
-            tenantSites.push(new XOSTenantSite( { name: siteName, allocated: allocated, id: id} ));
+            ready = slice.attributes.site_ready[siteName] || 0;
+            tenantSites.push(new XOSTenantSite( { name: siteName, allocated: allocated, ready: ready, id: id} ));
             id = id + 1;
         }
         for (index in xos.tenantview.models[0].attributes.blessed_site_names) {
             siteName = xos.tenantview.models[0].attributes.blessed_site_names[index];
             if (! (siteName in slice.attributes.site_allocation)) {
-                tenantSites.push(new XOSTenantSite( { name: siteName, allocated: 0, id: id} ));
+                tenantSites.push(new XOSTenantSite( { name: siteName, allocated: 0, ready: 0, id: id} ));
                 id = id + 1;
             }
         }
         this.set(tenantSites);
+
+        var that=this;
+        this.listenTo(slice, 'change', function() { that.getReadyFromSlice(slice); })
+    },
+
+    getReadyFromSlice: function(slice) {
+        for (siteName in slice.attributes.site_ready) {
+            ready = slice.attributes.site_ready[siteName];
+            for (index in this.models) {
+                tenantSite = this.models[index];
+                if (tenantSite.attributes.name == siteName) {
+                    tenantSite.set("ready", ready);
+                }
+            }
+        }
+    },
+
+    putToSlice: function(slice) {
+        slice.attributes.site_allocation = {};
+        for (index in this.models) {
+            var model = this.models[index];
+            slice.attributes.site_allocation[ model.attributes.name ] = model.attributes.allocated;
+        }
     },
 });
 
+XOSEditUsersView = Marionette.ItemView.extend({
+            template: "#tenant-edit-users",
+            viewInitializers: [],
+
+            onShow: function() {
+                _.each(this.viewInitializers, function(initializer) {
+                    initializer();
+                });
+            },
+
+            templateHelpers: function() { return { detailView: this, model: this.model }; },
+
+            });
+
+XOSTenantSummaryView = XOSDetailView.extend({
+            events: {"change": "onChange"},
+
+            onChange: function(e) {
+                XOSTenantApp.setDirty(true);
+            },
+
+            saveSuccess: function() {
+                console.log("saveSuccess!");
+                XOSTenantApp.setDirty(false);
+            },
+
+            });
+
+
 XOSTenantButtonView = Marionette.ItemView.extend({
             template: "#xos-tenant-buttons-template",
 
@@ -35,27 +88,43 @@ XOSTenantButtonView = Marionette.ItemView.extend({
                      "click button.btn-tenant-delete": "deleteClicked",
                      "click button.btn-tenant-add-user": "addUserClicked",
                      "click button.btn-tenant-save": "saveClicked",
+                     "click button.btn-tenant-download-ssh": "downloadClicked",
                      },
 
             createClicked: function(e) {
+                     XOSTenantApp.addSlice();
                      },
 
             deleteClicked: function(e) {
-                     this.options.linkedView.deleteClicked.call(this.options.linkedView, e);
+                     XOSTenantApp.deleteSlice(this.options.linkedView.model);
                      },
 
             addUserClicked: function(e) {
+                     XOSTenantApp.editUsers(this.options.linkedView.model);
+                     },
+
+            downloadClicked: function(e) {
+                     XOSTenantApp.downloadSSH(this.options.linkedView.model);
                      },
 
             saveClicked: function(e) {
-                     this.options.linkedView.submitContinueClicked.call(this.options.linkedView, e);
+                     model = this.options.linkedView.model;
+                     model.tenantSiteCollection.putToSlice(model);
+                     model.attributes.users = model.usersBuffer;
+
+                     e.preventDefault();
+                     this.options.linkedView.save();
+                     //this.options.linkedView.submitContinueClicked.call(this.options.linkedView, e);
+                     //XOSTenantApp.setDirty(false);
                      },
             });
 
 XOSTenantApp = new XOSApplication({
     logTableId: "#logTable",
     statusMsgId: "#statusMsg",
-    hideTabsByDefault: true
+    hideTabsByDefault: true,
+    dirty: false,
+    varName: "XOSTenantApp",
 });
 
 XOSTenantApp.addRegions({
@@ -63,17 +132,45 @@ XOSTenantApp.addRegions({
     tenantSummary: "#tenantSummary",
     tenantSiteList: "#tenantSiteList",
     tenantButtons: "#tenantButtons",
+    tenantAddSliceInterior: "#tenant-addslice-interior",
+    tenantEditUsersInterior: "#tenant-edit-users-interior",
+    tenantSSHCommandsInterior: "#tenant-ssh-commands-interior",
 });
 
-XOSTenantApp.buildViews = function() {\r
+XOSTenantApp.setDirty = function(dirty) {
+    XOSTenantApp.dirty = dirty;
+    if (dirty) {
+        $("button.btn-tenant-save").addClass("btn-success");
+    } else {
+        $("button.btn-tenant-save").removeClass("btn-success");
+    }
+};
+
+XOSTenantApp.buildViews = function() {
      XOSTenantApp.tenantSites = new XOSTenantSiteCollection();\r
 \r
-     tenantSummaryClass = XOSDetailView.extend({template: "#xos-detail-template",\r
+     tenantSummaryClass = XOSTenantSummaryView.extend({template: "#xos-detail-template",\r
                                                 app: XOSTenantApp,\r
-                                                detailFields: ["serviceClass", "image_preference", "network_ports", "mount_data_sets"]});\r
+                                                detailFields: ["serviceClass", "default_image", "default_flavor", "network_ports"],\r
+                                                fieldDisplayNames: {serviceClass: "Service Level", "default_flavor": "Flavor", "default_image": "Image", "mount_data_sets": "Data Sets"},\r
+                                                helpText: {"serviceClass": "Existing slivers will be re-instantiated if changed",\r
+                                                           "default_image": "Existing slivers will be re-instantiated if changed",\r
+                                                           "default_flavor": "Existing slivers will be re-instantiated if changed"},\r
+\r
+                                                onShow: function() {\r
+                                                    // the slice selector is in a different table, so make every label cell the maximal width\r
+                                                    make_same_width("#xos-tenant-view-panel", ".xos-label-cell");\r
+                                                },\r
+                                                });\r
 \r
      XOSTenantApp.tenantSummaryView = tenantSummaryClass;\r
 \r
+     tenantAddClass = XOSDetailView.extend({template: "#xos-detail-template",\r
+                                                app: XOSTenantApp,\r
+                                                detailFields: ["name", "description"]});\r
+\r
+     XOSTenantApp.tenantAddView = tenantAddClass;\r
+\r
      tenantSiteItemClass = XOSItemView.extend({template: "#xos-listitem-template",\r
                                                app: XOSTenantApp});\r
 \r
@@ -86,14 +183,19 @@ XOSTenantApp.buildViews = function() {
                                                title: "sites",\r
                                                inputType: {allocated: "spinner"},\r
                                                noDeleteColumn: true,\r
+                                               disablePaginate: true,\r
+                                               disableFilter: true,\r
+                                               fieldDisplayNames: {"name": "Site"},\r
                                                });\r
 \r
      XOSTenantApp.tenantSiteListView = tenantSiteListClass;\r
 \r
      XOSTenantApp.tenantSliceSelectorView = SliceSelectorView.extend( {\r
          sliceChanged: function(id) {\r
-             //console.log("navigate to " + id);\r
-             XOSTenantApp.Router.navigate("slice/" + id, {trigger: true});\r
+             XOSTenantApp.navToSlice(id);\r
+         },\r
+         filter: function(slice) {\r
+             return slice.attributes.current_user_can_see;\r
          },\r
      });\r
 \r
@@ -109,78 +211,221 @@ make_choices = function(list_of_names, list_of_values) {
             displayName = list_of_names[index];\r
             result.push( [displayName, displayName] );\r
         }\r
+    } else {\r
+        for (index in list_of_names) {\r
+            displayName = list_of_names[index];\r
+            id = list_of_values[index];\r
+            result.push( [displayName, id] );\r
+        }\r
     }\r
     return result;\r
 };\r
 \r
+XOSTenantApp.navToSlice = function(id) {\r
+    XOSTenantApp.viewSlice(xos.slicesPlus.get(id));\r
+};\r
+\r
+XOSTenantApp.adjustCollectionField = function(collectionName, id, fieldName, amount) {\r
+    model = XOSTenantApp[collectionName].get(id);\r
+    model.set(fieldName, Math.max(model.get(fieldName) + amount, 0));\r
+    XOSTenantApp.setDirty(true);\r
+};\r
+\r
+XOSTenantApp.addSlice = function() {\r
+    var app=this;\r
+\r
+    if (!xos.tenant().current_user_can_create_slice) {\r
+        window.alert("You do not have sufficient rights to create a slice on your site");\r
+        return;\r
+    }\r
+\r
+    model = new xos.slicesPlus.model({site: xos.tenant().current_user_site_id,\r
+                                      name: xos.tenant().current_user_login_base + "_",\r
+                                      creator: xos.tenant().current_user_id});\r
+    console.log(model);\r
+    var detailView = new XOSTenantApp.tenantAddView({model: model,\r
+                                                     collection: xos.slicesPlus,\r
+                                                     noSubmitButton: true,\r
+                                                    });\r
+    detailView.dialog = $("#tenant-addslice-dialog");\r
+    app.tenantAddSliceInterior.show(detailView);\r
+    $("#tenant-addslice-dialog").dialog({\r
+       autoOpen: false,
+       modal: true,
+       width: 640,
+       buttons : {
+            "Create Slice" : function() {
+              var addDialog = this;
+              console.log("SAVE!!!");
+              detailView.synchronous = true;
+              detailView.afterSave = function() { $(addDialog).dialog("close"); XOSTenantApp.navToSlice(detailView.model.id); }
+              detailView.save();
+            },
+            "Cancel" : function() {
+              $(this).dialog("close");
+            }
+          }
+        });
+    $("#tenant-addslice-dialog").dialog("open");\r
+};\r
+\r
+XOSTenantApp.editUsers = function(model) {\r
+    var app=this;\r
+    var detailView = new XOSEditUsersView({model: model, collection: xos.slicesPlus});\r
+    detailView.dialog = $("#tenant-edit-users-dialog");\r
+    app.tenantEditUsersInterior.show(detailView);\r
+    $("#tenant-edit-users-dialog").dialog({\r
+       autoOpen: false,
+       modal: true,
+       width: 640,
+       buttons : {
+            "Ok" : function() {
+              var editDialog = this;
+              user_ids = all_options($("#tenant-edit-users-dialog").find(".select-picker-to"));
+              user_ids = user_ids.map( function(x) { return parseInt(x,10); } );
+              if (!array_same_elements(user_ids, model.usersBuffer)) {
+                  XOSTenantApp.setDirty(true);
+              }
+              model.usersBuffer = user_ids;
+              $(editDialog).dialog("close");
+            },
+            "Cancel" : function() {
+              $(this).dialog("close");
+            }
+          }
+        });
+    $("#tenant-edit-users-dialog").dialog("open");\r
+};\r
+\r
+XOSTenantApp.downloadSSHOld = function(model) {\r
+    sshCommands = "";\r
+    for (index in model.attributes.sliceInfo.sshCommands) {\r
+         sshCommand = model.attributes.sliceInfo.sshCommands[index];\r
+         sshCommands = sshCommands + sshCommand + "\n";\r
+    }\r
+\r
+    if (sshCommands.length == 0) {\r
+         alert("this slice has no instantiated slivers yet");\r
+         return;\r
+    }\r
+\r
+    var myWindow = window.open("", "ssh_command_list",""); // "width=640, height=480");\r
+    myWindow.document.write("<html><head><title>SSH Commands</title></head><body><pre>" + sshCommands + "</pre></body></html>");\r
+    myWindow.document.close();\r
+};\r
+\r
+XOSTenantApp.downloadSSH = function(model) {\r
+    sshCommands = "";\r
+    for (index in model.attributes.sliceInfo.sshCommands) {\r
+         sshCommand = model.attributes.sliceInfo.sshCommands[index];\r
+         sshCommands = sshCommands + sshCommand + "\n";\r
+    }\r
+\r
+    if (sshCommands.length == 0) {\r
+         alert("this slice has no instantiated slivers yet");\r
+         return;\r
+    }\r
+\r
+    var htmlView = new HTMLView({html: '<pre style="overflow: auto; word-wrap: normal; white-space: pre; word-wrap: normal;">' + sshCommands + '</pre>'});\r
+    XOSTenantApp.tenantSSHCommandsInterior.show(htmlView);\r
+\r
+    $("#tenant-ssh-commands-dialog").dialog({\r
+       autoOpen: false,
+       modal: true,
+       width: 640,
+       buttons : {
+            "Ok" : function() {
+              $(this).dialog("close");
+            },
+          }
+        });
+    $("#tenant-ssh-commands-dialog").dialog("open");\r
+};\r
+\r
+XOSTenantApp.deleteSlice = function(model) {\r
+    var app=this;\r
+    app.deleteDialog(model, function() { console.log("afterDelete"); app.viewSlice(undefined); });\r
+};\r
+\r
 XOSTenantApp.viewSlice = function(model) {\r
+    if (XOSTenantApp.dirty) {\r
+        if (!confirm("The current sliver has unsaved data -- view new sliver anyway ?")) {\r
+            $("#tenantSliceSelector select").val(XOSTenantApp.currentSlice.id);\r
+            return;\r
+        }\r
+    }\r
+\r
+    XOSTenantApp.setDirty(false);\r
+\r
     if (!model && xos.slicesPlus.models.length > 0) {\r
         model = xos.slicesPlus.models[0];\r
     }\r
 \r
-    sliceSelector = new XOSTenantApp.tenantSliceSelectorView({collection: xos.slicesPlus,\r
-                                                              selectedID: model.id,\r
-                                                             } );\r
-    XOSTenantApp.sliceSelector = sliceSelector;\r
-    XOSTenantApp.tenantSliceSelector.show(sliceSelector);\r
+    if (model) {\r
+        sliceSelector = new XOSTenantApp.tenantSliceSelectorView({collection: xos.slicesPlus,\r
+                                                                  selectedID: model ? model.id : null,\r
+                                                                 } );\r
+        XOSTenantApp.sliceSelector = sliceSelector;\r
+        XOSTenantApp.tenantSliceSelector.show(sliceSelector);\r
 \r
-    tenantSummary = new XOSTenantApp.tenantSummaryView({model: model,\r
-                                                        choices: {mount_data_sets: make_choices(xos.tenantview.models[0].attributes.public_volume_names, null),\r
-                                                                  image_preference: make_choices(xos.tenantview.models[0].attributes.blessed_image_names, null)},\r
-                                                       });\r
-    XOSTenantApp.tenantSummary.show(tenantSummary);\r
+        tenantSummary = new XOSTenantApp.tenantSummaryView({model: model,\r
+                                                            choices: {mount_data_sets: make_choices(xos.tenant().public_volume_names, null),\r
+                                                                      serviceClass: make_choices(xos.tenant().blessed_service_class_names, xos.tenant().blessed_service_classes),\r
+                                                                      default_image: make_choices(xos.tenant().blessed_image_names, xos.tenant().blessed_images),\r
+                                                                      default_flavor: make_choices(xos.tenant().blessed_flavor_names, xos.tenant().blessed_flavors),},\r
+                                                           });\r
+        XOSTenantApp.tenantSummary.show(tenantSummary);\r
 \r
-    tenantSites = new XOSTenantSiteCollection();\r
-    tenantSites.updateFromSlice(model);\r
-    XOSTenantApp.tenantSites = tenantSites;\r
+        tenantSites = new XOSTenantSiteCollection();\r
+        tenantSites.getFromSlice(model);\r
+        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
+        model.usersOrig = model.attributes.users;   /* save an immutable copy that we'll use for username lookups */\r
+        model.user_namesOrig = model.attributes.user_names;\r
+        model.tenantSiteCollection = tenantSites;\r
+        XOSTenantApp.tenantSites = tenantSites;\r
 \r
-    tenantSiteList = new XOSTenantApp.tenantSiteListView({collection: tenantSites });\r
-    XOSTenantApp.tenantSiteList.show(tenantSiteList);\r
-    // on xos.slicePlus.sort, need to update xostenantapp.tenantSites\r
+        tenantSiteList = new XOSTenantApp.tenantSiteListView({collection: tenantSites });\r
+        XOSTenantApp.tenantSiteList.show(tenantSiteList);\r
+        // on xos.slicePlus.sort, need to update xostenantapp.tenantSites\r
 \r
-    XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { app: XOSTenantApp,\r
-                                                                linkedView: tenantSummary } ) );\r
-};\r
+        XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { app: XOSTenantApp,\r
+                                                                    linkedView: tenantSummary } ) );\r
 \r
-XOSTenantApp.initRouter = function() {\r
-    router = XOSRouter;\r
-    var api = {};\r
-    var routes = {};\r
-\r
-    nav_url = "slice/:id";\r
-    api_command = "viewSlice";\r
-    api[api_command] = function(id) { XOSTenantApp.viewSlice(xos.slicesPlus.get(id)); };\r
-    routes[nav_url] = api_command;\r
-\r
-    nav_url = "increase/:collectionName/:id/:fieldName";\r
-    api_command = "increase";\r
-    api[api_command] = function(collectionName, id, fieldName) {\r
-                           XOSTenantApp.Router.showPreviousURL();\r
-                           model = XOSTenantApp[collectionName].get(id);\r
-                           model.set(fieldName, model.get(fieldName) + 1);\r
-                       };\r
-    routes[nav_url] = api_command;\r
-\r
-    nav_url = "decrease/:collectionName/:id/:fieldName";\r
-    api_command = "decrease";\r
-    api[api_command] = function(collectionName, id, fieldName) {\r
-                           XOSTenantApp.Router.showPreviousURL();\r
-                           model = XOSTenantApp[collectionName].get(id);\r
-                           model.set(fieldName, Math.max(0, model.get(fieldName) - 1));\r
-                       };\r
-    routes[nav_url] = api_command;\r
-\r
-    nav_url = "*path";\r
-    api_command = "defaultRoute";\r
-    api[api_command] = function() { XOSTenantApp.viewSlice(undefined); };\r
-    routes[nav_url] = api_command;\r
-\r
-    XOSTenantApp.Router = new router({ appRoutes: routes, controller: api });\r
+        XOSTenantApp.currentSlice = model;\r
+    } else {\r
+        XOSTenantApp.tenantSliceSelector.show(new HTMLView({html: ""}));\r
+        XOSTenantApp.tenantSummary.show(new HTMLView({html: "You have no slices"}));\r
+        XOSTenantApp.tenantSiteList.show(new HTMLView({html: ""}));\r
+        XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { template: "#xos-tenant-buttons-noslice-template",\r
+                                                                    app: XOSTenantApp,\r
+                                                                    linkedView: tenantSummary } ) );\r
+    }\r
 };\r
 \r
-XOSTenantApp.startNavigation = function() {\r
-    Backbone.history.start();\r
-    XOSTenantApp.navigationStarted = true;\r
+XOSTenantApp.sanityCheck = function() {\r
+    errors = [];\r
+    if (xos.tenant().blessed_service_classes.length == 0) {\r
+        errors.push("no blessed service classes");\r
+    }\r
+    if (xos.tenant().blessed_flavors.length == 0) {\r
+        errors.push("no blessed flavors");\r
+    }\r
+    if (xos.tenant().blessed_images.length == 0) {\r
+        errors.push("no blessed images");\r
+    }\r
+    if (xos.tenant().blessed_sites.length == 0) {\r
+        errors.push("no blessed sites");\r
+    }\r
+    if (xos.tenant().current_user_site_id == null) {\r
+        errors.push("current user does not have a site");\r
+    }\r
+\r
+    if (errors.length > 0) {\r
+         $("#tenantSummary").html("Tenant view sanity check failed<br>" + errors.join("<br>"));\r
+         return false;\r
+    }\r
+\r
+    return true;\r
 }\r
 \r
 XOSTenantApp.collectionLoadChange = function() {\r
@@ -188,11 +433,9 @@ XOSTenantApp.collectionLoadChange = function() {
 \r
     if (!XOSTenantApp.navigationStarted) {\r
         if (stats["isLoaded"] + stats["failedLoad"] >= stats["startedLoad"]) {\r
-            XOSTenantApp.startNavigation();\r
-\r
-            //if (xos.slicesPlus.models.length > 0) {\r
-            //    XOSTenantApp.Router.navigate("slice/" + xos.slicesPlus.models[0].id, {trigger:true});\r
-            //}\r
+            if (XOSTenantApp.sanityCheck()) {\r
+                XOSTenantApp.viewSlice(undefined);\r
+            }\r
         } else {\r
             $("#tenantSummary").html("<h3>Loading...</h3><div id='xos-startup-progress'></div>");\r
             $("#xos-startup-progress").progressbar({value: stats["completedLoad"], max: stats["startedLoad"]});\r
@@ -203,8 +446,6 @@ XOSTenantApp.collectionLoadChange = function() {
 XOSTenantApp.on("start", function() {\r
      XOSTenantApp.buildViews();
 
-     XOSTenantApp.initRouter();
-
      // fire it once to initially show the progress bar
      XOSTenantApp.collectionLoadChange();