Merge branch 'master' of ssh://git.planet-lab.org/git/plstackapi
diff --git a/planetstack/core/plus/sites.py b/planetstack/core/plus/sites.py
index c5dde52..f51fc1b 100644
--- a/planetstack/core/plus/sites.py
+++ b/planetstack/core/plus/sites.py
@@ -12,7 +12,7 @@
     def get_urls(self):
         """Add our dashboard view to the admin urlconf. Deleted the default index."""
         from django.conf.urls import patterns, url
-        from views import DashboardWelcomeView, DashboardAjaxView, SimulatorView, DashboardSummaryAjaxView, DashboardAddOrRemoveSliverView, DashboardUserSiteView, DashboardAnalyticsAjaxView, TenantViewData,TenantCreateSlice
+        from views import DashboardWelcomeView, DashboardAjaxView, SimulatorView, DashboardSummaryAjaxView, DashboardAddOrRemoveSliverView, DashboardUserSiteView, DashboardAnalyticsAjaxView, TenantViewData,TenantCreateSlice, TenantAddOrRemoveSliverView
 
         urls = super(AdminMixin, self).get_urls()
         del urls[0]
@@ -33,6 +33,8 @@
                     name="analytics"),
                url(r'^dashboardaddorremsliver/$', self.admin_view(DashboardAddOrRemoveSliverView.as_view()),
                     name="addorremsliver"),
+               url(r'^tenantaddorremsliver/$', self.admin_view(TenantAddOrRemoveSliverView.as_view()),
+                    name="tenantaddorremsliver"),
                url(r'^tenantview/$', self.admin_view(TenantViewData.as_view()),
                     name="tenantview"),
                url(r'^createnewslice/$', self.admin_view(TenantCreateSlice.as_view()),
diff --git a/planetstack/core/plus/views.py b/planetstack/core/plus/views.py
index 0078d91..4211a30 100644
--- a/planetstack/core/plus/views.py
+++ b/planetstack/core/plus/views.py
@@ -9,6 +9,7 @@
 from django.http import HttpResponse
 from django.core import urlresolvers
 import traceback
+import socket
 
 if os.path.exists("/home/smbaker/projects/vicci/cdn/bigquery"):
     sys.path.append("/home/smbaker/projects/vicci/cdn/bigquery")
@@ -213,6 +214,91 @@
     def get(self, request, **kwargs):
         return HttpResponse(json.dumps(getTenantSliceInfo(request.user, True)), mimetype='application/javascript')
 
+def tenant_increase_slivers(user, siteName, slice, count):
+        site = Site.objects.filter(name=siteName)
+	nodes = Node.objects.filter(site=site)
+	print nodes
+	site.usedNodes = []
+        site.freeNodes = []
+	sliceName = Slice.objects.get(name=slice)
+        for node in nodes:
+            usedNode = False
+            for sliver in node.slivers.all():
+                if sliver in Sliver.objects.filter(slice=sliceName):
+                    usedNode = True
+            if usedNode:
+                site.usedNodes.append(node)
+		print site.usedNodes
+            else:
+                site.freeNodes.append(node)
+	    print site
+  	    slices =Slice.objects.all()
+	    sliceName = Slice.objects.get(name=slice)
+	    test = Sliver.objects.filter(slice=sliceName)
+	    while (len(site.freeNodes) > 0) and (count > 0):
+             	node = site.freeNodes.pop()
+            	hostname = node.name
+            	sliver = Sliver(name=node.name,
+                            slice=sliceName,
+                            node=node,
+                            image = Image.objects.all()[0],
+                            creator = User.objects.get(email=user),
+                            deploymentNetwork=node.deployment,
+                            numberCores =1 )
+            	sliver.save()
+
+            	print "created sliver", sliver
+	    	print sliver.node
+            	print sliver.numberCores
+	    	site.usedNodes.append(node)
+	    	count = int(count) - 1
+
+def tenant_decrease_slivers(user, siteName, slice, count):
+        site = Site.objects.filter(name=siteName)
+        nodes = Node.objects.filter(site=site)
+        slices = Slice.objects.all()
+	site.usedNodes = []
+        site.freeNodes = []
+        sliceName = Slice.objects.get(name=slice)
+
+	for node in nodes:
+            usedNode = False
+            for sliver in node.slivers.all():
+                if sliver in Sliver.objects.filter(slice=sliceName):
+                    usedNode = True
+            if usedNode:
+                site.usedNodes.append(node)
+            else:
+                site.freeNodes.append(node)
+            print "used nodes", site.usedNodes
+            slices =Slice.objects.all()
+            sliceName = Slice.objects.get(name=slice)
+            test = Sliver.objects.filter(slice=sliceName)
+            while (count > 0):
+                node = site.usedNodes.pop()
+		print node
+		print count
+		for sliver in node.slivers.all():	
+			if sliver.slice in slices:
+                     		print "deleting sliver", sliver.slice
+                     		sliver.delete()
+            	site.freeNodes.append(node)
+            	count = int(count) - 1
+                print "deleted sliver", sliver
+
+class TenantAddOrRemoveSliverView(View):
+    def post(self, request, *args, **kwargs):
+        siteName = request.POST.get("siteName", "0")
+        actionToDo = request.POST.get("actionToDo", "0")
+        count = request.POST.get("count","0")
+	slice = request.POST.get("slice","0")
+
+        if (actionToDo == "add"):
+            tenant_increase_slivers(request.user, siteName,slice, count)
+        elif (actionToDo == "rem"):
+            tenant_decrease_slivers(request.user,siteName,slice, count)
+        return HttpResponse('This is POST request ')
+
 class DashboardSummaryAjaxView(View):
     def get(self, request, **kwargs):
         return HttpResponse(json.dumps(hpc_wizard.get_hpc_wizard().get_summary_for_view()), mimetype='application/javascript')
diff --git a/planetstack/templates/admin/dashboard/tenant.html b/planetstack/templates/admin/dashboard/tenant.html
index bcf9cc9..83556fd 100644
--- a/planetstack/templates/admin/dashboard/tenant.html
+++ b/planetstack/templates/admin/dashboard/tenant.html
@@ -99,7 +99,7 @@
 			success: function (data) {
 				UserSliceTable(data);
 				showSliceData(data);
-                                $("#tooltip").css("display","none");
+				$("#tooltip").css("display", "none");
 			},
 			complete: function () {}
 		});
@@ -129,17 +129,19 @@
 				showSliceData(data);
 			});
 			$("#advanced-tenant").click(function () {
+				var selectedValue = $("#tenantSliceDropDown").val();
 				$("#tenantSliceDataWrapper").toggle();
 				$("#advancedTenantSliceDataWrapper").toggle();
 				$("#advTenantSiteTable").toggle();
 				$("#tenantSiteTable").toggle();
 				$("#sliver-btn").toggle();
 				$("#save-btn").toggle();
-				$('#adv-slice-name-value').empty();
+				//$('#adv-slice-name-value').empty();
 				$("<select></select>").attr('id', 'advTenantSliceDropDown').appendTo('#adv-slice-name-value');
 				for (row in rows) {
 					$("#advTenantSliceDropDown").append("<option>" + rows[row]['sliceName'] + "</option>");
 				}
+				$("#advTenantSliceDropDown").val(selectedValue);
 				advShowSliceData(data);
 				editSliverAdv();
 				$('#advTenantSliceDropDown').on('change', function () {
@@ -150,9 +152,9 @@
 				function editSliverAdv() {
 					$(".edit-view").click(function () {
 						var allocatedSlivers = parseInt($(this).parent().siblings(".allocated").html());
-						var td=$(this).parent().siblings(".allocated");
-						var pos =oTable.fnGetPosition(td[0]);
-  						$("#adv-dialog-form").dialog({
+						var td = $(this).parent().siblings(".allocated");
+						var pos = oTable.fnGetPosition(td[0]);
+						$("#adv-dialog-form").dialog({
 							autoOpen: false,
 							height: 200,
 							width: 350,
@@ -160,13 +162,13 @@
 							buttons: {
 								"Add": function () {
 									allocatedSlivers += parseInt($("#advNumOfSlivers").val());
-    									$(this).dialog("close");
+									$(this).dialog("close");
 									td.html(allocatedSlivers);
 								},
 								"Remove": function () {
-                                                                        allocatedSlivers -= parseInt($("#advNumOfSlivers").val());
-                                                                        $(this).dialog("close");
-                                                                        td.html(allocatedSlivers);
+									allocatedSlivers -= parseInt($("#advNumOfSlivers").val());
+									$(this).dialog("close");
+									td.html(allocatedSlivers);
 								}
 							}
 						});
@@ -190,34 +192,80 @@
 					var rows = data['userSliceInfo']['rows'];
 					var siteNames = [];
 					var sliverCount;
-                                        var tableData ={};
+					var tableData = {};
 					for (row in rows) {
 						if (rows[row]['sliceName'] == value) {
 							var innerRows = rows[row]['sliceSite'];
 							for (innerRow in innerRows) {
-								tableData[innerRow]=innerRows[innerRow];
+								tableData[innerRow] = innerRows[innerRow];
 							}
 						}
 					}
 					for (row in siteRows) {
-						var entry =siteRows[row]['siteName'];
+						var entry = siteRows[row]['siteName'];
 						if (!(entry in tableData)) {
 							tableData[siteRows[row]['siteName']] = 0;
 						}
 					}
-					for (row in tableData){
+					for (row in tableData) {
 						siteNames.push([row, tableData[row], '<a href="#" class="edit-view">Edit</a>']);
 					}
-					
+                                        $("#save-btn").click(function () {
+                                                  	var newTableData={};
+							var newSite = $(".siteName");
+							var newAllocated = $(".allocated");
+							for(i=1; i<newSite.length; i++){
+								newTableData[$($(".siteName")[i]).text()]=$($(".allocated")[i]).text();
+							}
+							for(newRow in newTableData){
+								if(newTableData[newRow] > tableData[newRow]){
+                                                                       $.ajax({
+       										url : '/tenantaddorremsliver/',
+        									dataType : 'json',
+        									data: {
+											siteName: newRow,
+											count : newTableData[newRow] - tableData[newRow],
+											slice : $("#advTenantSliceDropDown").val(),
+               									actionToDo: "add",
+               									csrfmiddlewaretoken: "{{ csrf_token }}",   // < here 
+               									state:"inactive" },
+        									type : 'POST',
+    								                complete:function(){
+            										location.reload();
+        									}
+    									});
+								}
+								else if(newTableData[newRow] < tableData[newRow]){
+                                                                       $.ajax({
+                                                                                url : '/tenantaddorremsliver/',
+                                                                                dataType : 'json',
+                                                                                data: {
+                                                                                        siteName: newRow,
+                                                                                        count : tableData[newRow] - newTableData[newRow],
+                                                                                        slice : $("#advTenantSliceDropDown").val(),
+                                                                                actionToDo: "rem",
+                                                                                csrfmiddlewaretoken: "{{ csrf_token }}",   // < here
+                                                                                state:"inactive" },
+                                                                                type : 'POST',
+                                                                                complete:function(){
+                                                                                        location.reload();
+                                                                                }
+                                                                        });
+                                                                }
+
+							}
+                        		});
 					oTable = $('#advTenantSiteTableData').dataTable({
 						"bJQueryUI": true,
 						"bFilter": false,
 						"bInfo": false,
 						"bLengthChange": false,
+						"bPaginate": false,
 						"aaData": siteNames,
 						"bStateSave": true,
 						"aoColumns": [{
-							"sTitle": "Site Name"
+							"sTitle": "Site Name",
+							sClass: "siteName"
 						}, {
 							"sTitle": "Allocated",
 							sClass: "alignCenter allocated"
@@ -271,50 +319,48 @@
 				for (row in imageData) {
 					$("#new-image").append("<option>" + imageData[row]['Image'] + "</option>");
 				}
-				var nameOfSlice= $("#new-slice-name").val();
+				var nameOfSlice = $("#new-slice-name").val();
 				var nameOfServiceClass = $("#new-service-class").val();
 				var nameOfImage = $("#new-image").val();
 				$("#create-slice-form").dialog({
-						autoOpen: false,
-						height: 300,
-						width: 350,
-						modal: true,
-						buttons: {
-							"Submit": function () {
-								$.ajax({
-									url: '/createnewslice/',
-									dataType: 'json',
-									data: {
-										sliceName: $("#new-slice-name").val(),
-										serviceClass: nameOfServiceClass,
-                                                                                imageName: nameOfImage,
-										actionToDo: "add",
-										csrfmiddlewaretoken: "{{ csrf_token }}", // < here 
-										state: "inactive"
-									},
-									type: 'POST',
-									beforeSend: function(){
-										if (!$("#new-slice-name").val()) {
-											$("#tooltip").css("display","block");
-											return false;
-										}
-                                                                                else{
-           										return true;
-										}
-									},
-									success: function (response) {
-									},
-									complete: function () {
-                                                                             location.reload();
-                                                                        }
-								});
-							},
-							Cancel: function () {
-								$(this).dialog("close");
-							}
+					autoOpen: false,
+					height: 300,
+					width: 350,
+					modal: true,
+					buttons: {
+						"Submit": function () {
+							$.ajax({
+								url: '/createnewslice/',
+								dataType: 'json',
+								data: {
+									sliceName: $("#new-slice-name").val(),
+									serviceClass: nameOfServiceClass,
+									imageName: nameOfImage,
+									actionToDo: "add",
+									csrfmiddlewaretoken: "{{ csrf_token }}", // < here 
+									state: "inactive"
+								},
+								type: 'POST',
+								beforeSend: function () {
+									if (!$("#new-slice-name").val()) {
+										$("#tooltip").css("display", "block");
+										return false;
+									} else {
+										return true;
+									}
+								},
+								success: function (response) {},
+								complete: function () {
+									location.reload();
+								}
+							});
+						},
+						Cancel: function () {
+							$(this).dialog("close");
 						}
-					});
-					$("#create-slice-form").dialog("open");
+					}
+				});
+				$("#create-slice-form").dialog("open");
 			});
 		}
 	}