blob: 2b015ef09bb7a970364d344674f3e8c1045bd9d9 [file] [log] [blame]
Siobhan Tullycf04fb62014-01-11 11:25:57 -05001#views.py
Scott Bakerbd57a432014-04-14 16:12:15 -07002import functools
3import math
Scott Baker771819b2014-03-19 22:10:17 -07004import os
5import sys
Siobhan Tully06d2c032014-02-23 23:48:52 -05006from django.views.generic import TemplateView, View
7import datetime
Scott Baker771819b2014-03-19 22:10:17 -07008from pprint import pprint
9import json
Scott Baker537d8232014-04-08 23:40:56 -070010from core.models import *
Scott Bakerbd57a432014-04-14 16:12:15 -070011from operator import attrgetter
12from django.views.decorators.csrf import csrf_exempt
13from django.http import HttpResponse, HttpResponseServerError
Scott Baker537d8232014-04-08 23:40:56 -070014from django.core import urlresolvers
Scott Bakerbd57a432014-04-14 16:12:15 -070015from django.contrib.gis.geoip import GeoIP
16from ipware.ip import get_ip
Scott Baker771819b2014-03-19 22:10:17 -070017import traceback
Scott Baker6253dfc2014-04-14 09:29:30 -070018import socket
Siobhan Tully06d2c032014-02-23 23:48:52 -050019
Scott Bakera880bb52014-04-14 23:52:48 -070020BLESSED_SITES = ["Stanford", "Washington", "Princeton", "GeorgiaTech", "MaxPlanck"]
21
Scott Baker771819b2014-03-19 22:10:17 -070022if os.path.exists("/home/smbaker/projects/vicci/cdn/bigquery"):
23 sys.path.append("/home/smbaker/projects/vicci/cdn/bigquery")
24else:
25 sys.path.append("/opt/planetstack/hpc_wizard")
26import hpc_wizard
Scott Baker75095b62014-04-21 17:32:09 -070027from planetstack_analytics import DoPlanetStackAnalytics, PlanetStackAnalytics, RED_LOAD, BLUE_LOAD
Siobhan Tullycf04fb62014-01-11 11:25:57 -050028
29class DashboardWelcomeView(TemplateView):
30 template_name = 'admin/dashboard/welcome.html'
31
32 def get(self, request, *args, **kwargs):
33 context = self.get_context_data(**kwargs)
Scott Baker771819b2014-03-19 22:10:17 -070034 userDetails = getUserSliceInfo(request.user)
35 #context['site'] = userDetails['site']
Siobhan Tullycf04fb62014-01-11 11:25:57 -050036
Scott Baker771819b2014-03-19 22:10:17 -070037 context['userSliceInfo'] = userDetails['userSliceInfo']
38 context['cdnData'] = userDetails['cdnData']
Siobhan Tullycf04fb62014-01-11 11:25:57 -050039 return self.render_to_response(context=context)
Siobhan Tullye18b3442014-02-23 14:23:34 -050040
Scott Baker771819b2014-03-19 22:10:17 -070041def getUserSliceInfo(user, tableFormat = False):
42 userDetails = {}
43# try:
44# // site = Site.objects.filter(id=user.site.id)
45# // except:
46# // site = Site.objects.filter(name="Princeton")
47# // userDetails['sitename'] = site[0].name
48# // userDetails['siteid'] = site[0].id
49
50 userSliceData = getSliceInfo(user)
51 if (tableFormat):
52# pprint("******* GET USER SLICE INFO")
53 userDetails['userSliceInfo'] = userSliceTableFormatter(userSliceData)
54 else:
55 userDetails['userSliceInfo'] = userSliceData
Scott Baker75095b62014-04-21 17:32:09 -070056 userDetails['cdnData'] = getCDNOperatorData(wait=False);
Scott Baker771819b2014-03-19 22:10:17 -070057# pprint( userDetails)
58 return userDetails
59
Scott Baker537d8232014-04-08 23:40:56 -070060class TenantCreateSlice(View):
61 def post(self, request, *args, **kwargs):
62 sliceName = request.POST.get("sliceName", "0")
63 serviceClass = request.POST.get("serviceClass", "0")
64 imageName = request.POST.get("imageName", "0")
65 actionToDo = request.POST.get("actionToDo", "0")
66 print sliceName
67 if (actionToDo == "add"):
68 serviceClass = ServiceClass.objects.get(name=serviceClass)
69 site = request.user.site
70 #image = Image.objects.get(name=imageName)
71 newSlice = Slice(name=sliceName,serviceClass=serviceClass,site=site,imagePreference=imageName)
72 newSlice.save()
73 return newSlice
74
75
76def getTenantSliceInfo(user, tableFormat = False):
77 tenantSliceDetails = {}
78 tenantSliceData = getTenantInfo(user)
79 tenantServiceClassData = getServiceClassInfo(user)
80 if (tableFormat):
81 tenantSliceDetails['userSliceInfo'] = userSliceTableFormatter(tenantSliceData)
82 tenantSliceDetails['sliceServiceClass']=userSliceTableFormatter(tenantServiceClassData)
83 else:
84 tenantSliceDetails['userSliceInfo'] = tenantSliceData
85 tenantSliceDetails['sliceServiceClass']=userSliceTableFormatter(tenantServiceClassData)
86 tenantSliceDetails['image']=userSliceTableFormatter(getImageInfo(user))
87 tenantSliceDetails['network']=userSliceTableFormatter(getNetworkInfo(user))
88 tenantSliceDetails['deploymentSites']=userSliceTableFormatter(getDeploymentSites())
Scott Bakerb85c26b2014-04-18 11:25:32 -070089 tenantSliceDetails['sites'] = userSliceTableFormatter(getTenantSitesInfo())
90 tenantSliceDetails['mountDataSets'] = userSliceTableFormatter(getMountDataSets())
Scott Baker537d8232014-04-08 23:40:56 -070091 return tenantSliceDetails
92
93
94def getTenantInfo(user):
95 slices =Slice.objects.all()
96 userSliceInfo = []
97 for entry in slices:
98 sliceName = Slice.objects.get(id=entry.id).name
99 slice = Slice.objects.get(name=Slice.objects.get(id=entry.id).name)
100 sliceServiceClass = entry.serviceClass.name
101 preferredImage = entry.imagePreference
102 numSliver = 0
103 sliceImage=""
104 sliceSite = {}
105 for sliver in slice.slivers.all():
106 numSliver +=sliver.numberCores
107 # sliceSite[sliver.deploymentNetwork.name] =sliceSite.get(sliver.deploymentNetwork.name,0) + 1
Scott Bakera880bb52014-04-14 23:52:48 -0700108 if sliver.node.site.name in BLESSED_SITES:
Scott Bakera880bb52014-04-14 23:52:48 -0700109 sliceSite[sliver.node.site.name] = sliceSite.get(sliver.node.site.name,0) + 1
110 sliceImage = sliver.image.name
Scott Bakerb85c26b2014-04-18 11:25:32 -0700111 numSites = len(sliceSite)
112 userSliceInfo.append({'sliceName': sliceName,'sliceServiceClass': sliceServiceClass,'preferredImage':preferredImage,'numOfSites':numSites, 'sliceSite':sliceSite,'sliceImage':sliceImage,'numOfSlivers':numSliver})
Scott Baker537d8232014-04-08 23:40:56 -0700113 return userSliceInfo
114
115def getTenantSitesInfo():
116 tenantSiteInfo=[]
117 for entry in Site.objects.all():
Scott Bakera880bb52014-04-14 23:52:48 -0700118 if entry.name in BLESSED_SITES:
119 tenantSiteInfo.append({'siteName':entry.name})
Scott Baker537d8232014-04-08 23:40:56 -0700120 return tenantSiteInfo
121
Scott Baker771819b2014-03-19 22:10:17 -0700122def userSliceTableFormatter(data):
123# pprint(data)
124 formattedData = {
125 'rows' : data
126 }
127 return formattedData
128
Scott Baker537d8232014-04-08 23:40:56 -0700129def getServiceClassInfo(user):
130 serviceClassList = ServiceClass.objects.all()
131 sliceInfo = []
132 for entry in serviceClassList:
133 sliceInfo.append({'serviceClass':entry.name})
134 return sliceInfo
135
136def getImageInfo(user):
Scott Bakerb85c26b2014-04-18 11:25:32 -0700137 #imageList = Image.objects.all()
138 imageList = ['Fedora 16 LXC rev 1.3','Hadoop','MPI']
Scott Baker537d8232014-04-08 23:40:56 -0700139 imageInfo = []
140 for imageEntry in imageList:
Scott Bakerb85c26b2014-04-18 11:25:32 -0700141 #imageInfo.append({'Image':imageEntry.name})
142 imageInfo.append({'Image':imageEntry})
Scott Baker537d8232014-04-08 23:40:56 -0700143 return imageInfo
144
Scott Bakerb85c26b2014-04-18 11:25:32 -0700145def getMountDataSets():
146 dataSetList = ['GenBank','LSST','LHC','NOAA','Measurement Lab','Common Crawl']
147 dataSetInfo = []
148 for entry in dataSetList:
149 dataSetInfo.append({'DataSet':entry})
150 return dataSetInfo
151
Scott Baker537d8232014-04-08 23:40:56 -0700152def getNetworkInfo(user):
153 #networkList = Network.objects.all()
154 networkList = ['Private Only','Private and Publicly Routable']
155 networkInfo = []
156 for networkEntry in networkList:
157 #networkInfo.append({'Network':networkEntry.name})
158 networkInfo.append({'Network':networkEntry})
159 return networkInfo
160
161def getDeploymentSites():
162 deploymentList = Deployment.objects.all()
163 deploymentInfo = []
164 for entry in deploymentList:
165 deploymentInfo.append({'DeploymentSite':entry.name})
166 return deploymentInfo
167
Scott Baker771819b2014-03-19 22:10:17 -0700168def getSliceInfo(user):
Siobhan Tully06d2c032014-02-23 23:48:52 -0500169 sliceList = Slice.objects.all()
Scott Baker771819b2014-03-19 22:10:17 -0700170 slicePrivs = SlicePrivilege.objects.filter(user=user)
Siobhan Tully06d2c032014-02-23 23:48:52 -0500171 userSliceInfo = []
172 for entry in slicePrivs:
Siobhan Tullye18b3442014-02-23 14:23:34 -0500173
Scott Baker771819b2014-03-19 22:10:17 -0700174 slicename = Slice.objects.get(id=entry.slice.id).name
Scott Baker537d8232014-04-08 23:40:56 -0700175 slice = Slice.objects.get(name=Slice.objects.get(id=entry.slice.id).name)
176 sliverList=Sliver.objects.all()
177 sites_used = {}
178 for sliver in slice.slivers.all():
179 #sites_used['deploymentSites'] = sliver.node.deployment.name
180 # sites_used[sliver.image.name] = sliver.image.name
181 sites_used[sliver.node.site.name] = sliver.numberCores
Scott Baker771819b2014-03-19 22:10:17 -0700182 sliceid = Slice.objects.get(id=entry.slice.id).id
Siobhan Tully06d2c032014-02-23 23:48:52 -0500183 try:
Scott Baker771819b2014-03-19 22:10:17 -0700184 sliverList = Sliver.objects.filter(slice=entry.slice.id)
185 siteList = {}
186 for x in sliverList:
187 if x.node.site not in siteList:
188 siteList[x.node.site] = 1
189 slivercount = len(sliverList)
190 sitecount = len(siteList)
Siobhan Tully06d2c032014-02-23 23:48:52 -0500191 except:
Scott Baker771819b2014-03-19 22:10:17 -0700192 traceback.print_exc()
193 slivercount = 0
194 sitecount = 0
Siobhan Tully06d2c032014-02-23 23:48:52 -0500195
Scott Baker771819b2014-03-19 22:10:17 -0700196 userSliceInfo.append({'slicename': slicename, 'sliceid':sliceid,
Scott Baker537d8232014-04-08 23:40:56 -0700197 'sitesUsed':sites_used,
198 'role': SliceRole.objects.get(id=entry.role.id).role,
199 'slivercount': slivercount,
200 'sitecount':sitecount})
Scott Baker771819b2014-03-19 22:10:17 -0700201
Siobhan Tully06d2c032014-02-23 23:48:52 -0500202 return userSliceInfo
203
Scott Baker75095b62014-04-21 17:32:09 -0700204def getCDNOperatorData(randomizeData = False, wait=True):
205 HPC_SLICE_NAME = "HyperCache"
206
Scott Baker0017c102014-04-18 10:48:31 -0700207 bq = PlanetStackAnalytics()
Siobhan Tully06d2c032014-02-23 23:48:52 -0500208
Scott Baker75095b62014-04-21 17:32:09 -0700209 rows = bq.get_cached_query_results(bq.compose_latest_query(groupByFields=["%hostname", "event", "%slice"]), wait)
Siobhan Tully06d2c032014-02-23 23:48:52 -0500210
Scott Baker75095b62014-04-21 17:32:09 -0700211 # if wait==False, then we could have no rows yet
Scott Baker0017c102014-04-18 10:48:31 -0700212
Scott Baker75095b62014-04-21 17:32:09 -0700213 stats_rows = {}
214 if rows:
215 rows = bq.postprocess_results(rows, filter={"slice": HPC_SLICE_NAME}, maxi=["cpu"], count=["hostname"], computed=["bytes_sent/elapsed"], groupBy=["Time","site"], maxDeltaTime=80)
Scott Baker0017c102014-04-18 10:48:31 -0700216
Scott Baker75095b62014-04-21 17:32:09 -0700217 # dictionaryize the statistics rows by site name
218 stats_rows = {}
219 for row in rows:
220 stats_rows[row["site"]] = row
Scott Baker0017c102014-04-18 10:48:31 -0700221
Scott Baker75095b62014-04-21 17:32:09 -0700222 slice = Slice.objects.get(name=HPC_SLICE_NAME)
223 slice_slivers = list(slice.slivers.all())
Scott Baker0017c102014-04-18 10:48:31 -0700224
225 new_rows = {}
Scott Baker75095b62014-04-21 17:32:09 -0700226 for site in Site.objects.all():
227 # compute number of slivers allocated in the data model
228 allocated_slivers = 0
229 for sliver in slice_slivers:
230 if sliver.node.site == site:
231 allocated_slivers = allocated_slivers + 1
232
233 stats_row = stats_rows.get(site.name,{})
234
235 max_cpu = stats_row.get("max_avg_cpu", stats_row.get("max_cpu",0))
236 cpu=float(max_cpu)/100.0
237 hotness = max(0.0, ((cpu*RED_LOAD) - BLUE_LOAD)/(RED_LOAD-BLUE_LOAD))
238
239 # format it to what that CDN Operations View is expecting
240 new_row = {"lat": float(site.location.longitude),
241 "long": float(site.location.longitude),
242 "lat": float(site.location.latitude),
Scott Baker0017c102014-04-18 10:48:31 -0700243 "health": 0,
Scott Baker75095b62014-04-21 17:32:09 -0700244 "numNodes": int(site.nodes.count()),
245 "activeHPCSlivers": int(stats_row.get("count_hostname", 0)), # measured number of slivers, from bigquery statistics
246 "numHPCSlivers": allocated_slivers, # allocated number of slivers, from data model
247 "siteUrl": str(site.site_url),
248 "bandwidth": stats_row.get("sum_computed_bytes_sent_div_elapsed",0),
249 "load": max_cpu,
250 "hot": float(hotness)}
251 new_rows[str(site.name)] = new_row
252
253 # get rid of sites with 0 slivers that overlap other sites with >0 slivers
254 for (k,v) in new_rows.items():
255 bad=False
256 if v["numHPCSlivers"]==0:
257 for v2 in new_rows.values():
258 if (v!=v2) and (v2["numHPCSlivers"]>=0):
259 d = haversine(v["lat"],v["long"],v2["lat"],v2["long"])
260 if d<100:
261 bad=True
262 if bad:
263 del new_rows[k]
Scott Baker0017c102014-04-18 10:48:31 -0700264
265 return new_rows
Siobhan Tully06d2c032014-02-23 23:48:52 -0500266
Scott Baker771819b2014-03-19 22:10:17 -0700267class SimulatorView(View):
268 def get(self, request, **kwargs):
269 sim = json.loads(file("/tmp/simulator.json","r").read())
270 text = "<html><head></head><body>"
271 text += "Iteration: %d<br>" % sim["iteration"]
272 text += "Elapsed since report %d<br><br>" % sim["elapsed_since_report"]
273 text += "<table border=1>"
274 text += "<tr><th>site</th><th>trend</th><th>weight</th><th>bytes_sent</th><th>hot</th></tr>"
275 for site in sim["site_load"].values():
276 text += "<tr>"
277 text += "<td>%s</td><td>%0.2f</td><td>%0.2f</td><td>%d</td><td>%0.2f</td>" % \
278 (site["name"], site["trend"], site["weight"], site["bytes_sent"], site["load_frac"])
279 text += "</tr>"
280 text += "</table>"
281 text += "</body></html>"
282 return HttpResponse(text)
283
284class DashboardUserSiteView(View):
285 def get(self, request, **kwargs):
286 return HttpResponse(json.dumps(getUserSliceInfo(request.user, True)), mimetype='application/javascript')
287
Scott Baker537d8232014-04-08 23:40:56 -0700288class TenantViewData(View):
289 def get(self, request, **kwargs):
290 return HttpResponse(json.dumps(getTenantSliceInfo(request.user, True)), mimetype='application/javascript')
291
Scott Baker75095b62014-04-21 17:32:09 -0700292def haversine(site_lat, site_lon, lat, lon):
293 site_lat = float(site_lat)
294 site_lon = float(site_lon)
295 lat = float(lat)
296 lon = float(lon)
297 d=0
298 if lat and lon and site_lat and site_lon:
299 R = 6378.1
300 a = math.sin( math.radians((lat - site_lat)/2.0) )**2 + math.cos( math.radians(lat) )*math.cos( math.radians(site_lat) )*(math.sin( math.radians((lon - site_lon)/2.0 ) )**2)
301 c = 2 * math.atan2( math.sqrt(a), math.sqrt(1 - a) )
302 d = R * c
303
304 return d
305
Scott Bakerbd57a432014-04-14 16:12:15 -0700306def siteSortKey(site, slice=None, count=None, lat=None, lon=None):
307 # try to pick a site we're already using
308 has_slivers_here=False
309 if slice:
310 for sliver in slice.slivers.all():
311 if sliver.node.site.name == site.name:
312 has_slivers_here=True
313
314 # Haversine method
Scott Baker75095b62014-04-21 17:32:09 -0700315 d = haversine(site.location.latitude, site.location.longitude, lat, lon)
Scott Bakerbd57a432014-04-14 16:12:15 -0700316
317 return (-has_slivers_here, d)
318
319def tenant_pick_sites(user, user_ip=None, slice=None, count=None):
320 """ Returns list of sites, sorted from most favorable to least favorable """
321 lat=None
322 lon=None
323 try:
324 client_geo = GeoIP().city(user_ip)
325 if client_geo:
326 lat=float(client_geo["latitude"])
327 lon=float(client_geo["longitude"])
328 except:
329 print "exception in geo code"
330 traceback.print_exc()
331
332 sites = Site.objects.all()
Scott Bakera880bb52014-04-14 23:52:48 -0700333 sites = [x for x in sites if x.name in BLESSED_SITES]
Scott Bakerbd57a432014-04-14 16:12:15 -0700334 sites = sorted(sites, key=functools.partial(siteSortKey, slice=slice, count=count, lat=lat, lon=lon))
335
336 return sites
337
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700338def slice_increase_slivers(user, user_ip, siteList, slice, count, noAct=False):
Scott Bakere4deddd2014-04-14 16:48:05 -0700339 sitesChanged = {}
340
Scott Bakerbd57a432014-04-14 16:12:15 -0700341 # let's compute how many slivers are in use in each node of each site
342 for site in siteList:
343 site.nodeList = list(site.nodes.all())
344 for node in site.nodeList:
345 node.sliverCount = 0
Scott Baker6253dfc2014-04-14 09:29:30 -0700346 for sliver in node.slivers.all():
Scott Baker21511942014-04-15 17:44:27 -0700347 if sliver.slice.id == slice.id:
Scott Baker0017c102014-04-18 10:48:31 -0700348 node.sliverCount = node.sliverCount + 1
Scott Baker6253dfc2014-04-14 09:29:30 -0700349
Scott Bakerbd57a432014-04-14 16:12:15 -0700350 # Allocate slivers to nodes
351 # for now, assume we want to allocate all slivers from the same site
352 nodes = siteList[0].nodeList
353 while (count>0):
354 # Sort the node list by number of slivers per node, then pick the
355 # node with the least number of slivers.
356 nodes = sorted(nodes, key=attrgetter("sliverCount"))
357 node = nodes[0]
Scott Baker6253dfc2014-04-14 09:29:30 -0700358
Scott Bakerbd57a432014-04-14 16:12:15 -0700359 print "adding sliver at node", node.name, "of site", node.site.name
Scott Baker6253dfc2014-04-14 09:29:30 -0700360
Scott Bakere4deddd2014-04-14 16:48:05 -0700361 if not noAct:
362 sliver = Sliver(name=node.name,
363 slice=slice,
364 node=node,
365 image = Image.objects.all()[0],
366 creator = User.objects.get(email=user),
367 deploymentNetwork=node.deployment,
368 numberCores =1 )
369 sliver.save()
Scott Bakerbd57a432014-04-14 16:12:15 -0700370
371 node.sliverCount = node.sliverCount + 1
372
373 count = count - 1
374
Scott Bakere4deddd2014-04-14 16:48:05 -0700375 sitesChanged[node.site.name] = sitesChanged.get(node.site.name,0) + 1
376
377 return sitesChanged
378
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700379def slice_decrease_slivers(user, siteList, slice, count, noAct=False):
Scott Bakere4deddd2014-04-14 16:48:05 -0700380 sitesChanged = {}
Scott Bakerb85c26b2014-04-18 11:25:32 -0700381 sliverList ={}
Scott Bakerbd57a432014-04-14 16:12:15 -0700382 if siteList:
383 siteNames = [site.name for site in siteList]
384 else:
385 siteNames = None
386
387 for sliver in slice.slivers.all():
Scott Bakerb85c26b2014-04-18 11:25:32 -0700388 if(not siteNames) or (sliver.node.site.name in siteNames):
389 node = sliver.node
390 sliverList[sliver.name]=node.name
Scott Bakerbd57a432014-04-14 16:12:15 -0700391
Scott Bakerb85c26b2014-04-18 11:25:32 -0700392 for key in sliverList:
393 if count>0:
Scott Bakerf1b65c02014-04-21 01:03:17 -0700394 sliver = Sliver.objects.filter(name=key)[0]
Scott Bakerb85c26b2014-04-18 11:25:32 -0700395 sliver.delete()
396 print "deleting sliver",sliverList[key],"at node",sliver.node.name
397 count=count-1
Scott Bakerf1b65c02014-04-21 01:03:17 -0700398 sitesChanged[sliver.node.site.name] = sitesChanged.get(sliver.node.site.name,0) - 1
Scott Bakerb85c26b2014-04-18 11:25:32 -0700399
Scott Bakere4deddd2014-04-14 16:48:05 -0700400 return sitesChanged
401
Scott Bakerb85c26b2014-04-18 11:25:32 -0700402class TenantDeleteSliceView(View):
403 def post(self,request):
404 sliceName = request.POST.get("sliceName",None)
405 slice = Slice.objects.get(name=sliceName)
406 print slice, slice.id
407 sliceToDel=Slice(name=sliceName, id=slice.id)
408 sliceToDel.delete()
409
Scott Baker6253dfc2014-04-14 09:29:30 -0700410class TenantAddOrRemoveSliverView(View):
Scott Bakere4deddd2014-04-14 16:48:05 -0700411 """ Add or remove slivers from a Slice
412
413 Arguments:
414 siteName - name of site. If not specified, PlanetStack will pick the
415 best site.,
416 actionToDo - [add | rem]
417 count - number of slivers to add or remove
418 sliceName - name of slice
Scott Bakera880bb52014-04-14 23:52:48 -0700419 noAct - if set, no changes will be made to db, but result will still
420 show which sites would have been modified.
Scott Bakere4deddd2014-04-14 16:48:05 -0700421
422 Returns:
423 Dictionary of sites that were modified, and the count of nodes
424 that were added or removed at each site.
425 """
Scott Baker6253dfc2014-04-14 09:29:30 -0700426 def post(self, request, *args, **kwargs):
Scott Bakerbd57a432014-04-14 16:12:15 -0700427 siteName = request.POST.get("siteName", None)
428 actionToDo = request.POST.get("actionToDo", None)
429 count = int(request.POST.get("count","0"))
430 sliceName = request.POST.get("slice", None)
Scott Bakere4deddd2014-04-14 16:48:05 -0700431 noAct = request.POST.get("noAct", False)
Scott Bakerbd57a432014-04-14 16:12:15 -0700432
433 if not sliceName:
434 return HttpResponseServerError("No slice name given")
435
436 slice = Slice.objects.get(name=sliceName)
437
438 if siteName:
439 siteList = [Site.objects.get(name=siteName)]
440 else:
441 siteList = None
Scott Baker6253dfc2014-04-14 09:29:30 -0700442
443 if (actionToDo == "add"):
Scott Bakerbd57a432014-04-14 16:12:15 -0700444 user_ip = request.GET.get("ip", get_ip(request))
445 if (siteList is None):
446 siteList = tenant_pick_sites(user, user_ip, slice, count)
447
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700448 sitesChanged = slice_increase_slivers(request.user, user_ip, siteList, slice, count, noAct)
Scott Baker6253dfc2014-04-14 09:29:30 -0700449 elif (actionToDo == "rem"):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700450 sitesChanged = slice_decrease_slivers(request.user, siteList, slice, count, noAct)
Scott Bakerbd57a432014-04-14 16:12:15 -0700451 else:
452 return HttpResponseServerError("Unknown actionToDo %s" % actionToDo)
453
Scott Bakere4deddd2014-04-14 16:48:05 -0700454 return HttpResponse(json.dumps(sitesChanged), mimetype='application/javascript')
Scott Bakerbd57a432014-04-14 16:12:15 -0700455
456 def get(self, request, *args, **kwargs):
457 request.POST = request.GET
458 return self.post(request, *args, **kwargs) # for testing REST in browser
459 #return HttpResponseServerError("GET is not supported")
460
461class TenantPickSitesView(View):
462 """ primarily just for testing purposes """
463 def get(self, request, *args, **kwargs):
464 count = request.GET.get("count","0")
465 slice = request.GET.get("slice",None)
466 if slice:
467 slice = Slice.objects.get(name=slice)
468 ip = request.GET.get("ip", get_ip(request))
469 sites = tenant_pick_sites(request.user, user_ip=ip, count=0, slice=slice)
470 sites = [x.name for x in sites]
471 return HttpResponse(json.dumps(sites), mimetype='application/javascript')
Scott Baker6253dfc2014-04-14 09:29:30 -0700472
Scott Baker771819b2014-03-19 22:10:17 -0700473class DashboardSummaryAjaxView(View):
474 def get(self, request, **kwargs):
Scott Baker0017c102014-04-18 10:48:31 -0700475 def avg(x):
476 return float(sum(x))/len(x)
477
478 sites = getCDNOperatorData().values()
479
480 sites = [site for site in sites if site["numHPCSlivers"]>0]
481
482 total_slivers = sum( [site["numHPCSlivers"] for site in sites] )
483 total_bandwidth = sum( [site["bandwidth"] for site in sites] )
484 average_cpu = int(avg( [site["load"] for site in sites] ))
485
486 result= {"total_slivers": total_slivers,
487 "total_bandwidth": total_bandwidth,
488 "average_cpu": average_cpu}
489
490 return HttpResponse(json.dumps(result), mimetype='application/javascript')
Scott Baker771819b2014-03-19 22:10:17 -0700491
492class DashboardAddOrRemoveSliverView(View):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700493 # TODO: deprecate this view in favor of using TenantAddOrRemoveSliverView
494
Scott Baker771819b2014-03-19 22:10:17 -0700495 def post(self, request, *args, **kwargs):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700496 siteName = request.POST.get("site", None)
Scott Baker771819b2014-03-19 22:10:17 -0700497 actionToDo = request.POST.get("actionToDo", "0")
498
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700499 siteList = [Site.objects.get(name=siteName)]
500 slice = Slice.objects.get(name="HyperCache")
501
Scott Baker771819b2014-03-19 22:10:17 -0700502 if (actionToDo == "add"):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700503 user_ip = request.GET.get("ip", get_ip(request))
504 slice_increase_slivers(request.user, user_ip, siteList, slice, 1)
Scott Baker771819b2014-03-19 22:10:17 -0700505 elif (actionToDo == "rem"):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700506 slice_decrease_slivers(request.user, siteList, slice, 1)
Scott Baker771819b2014-03-19 22:10:17 -0700507
508 print '*' * 50
509 print 'Ask for site: ' + siteName + ' to ' + actionToDo + ' another HPC Sliver'
510 return HttpResponse('This is POST request ')
Siobhan Tully06d2c032014-02-23 23:48:52 -0500511
512class DashboardAjaxView(View):
513 def get(self, request, **kwargs):
514 return HttpResponse(json.dumps(getCDNOperatorData(True)), mimetype='application/javascript')
Scott Baker771819b2014-03-19 22:10:17 -0700515
516class DashboardAnalyticsAjaxView(View):
517 def get(self, request, name="hello_world", **kwargs):
518 if (name == "hpcSummary"):
519 return HttpResponse(json.dumps(hpc_wizard.get_hpc_wizard().get_summary_for_view()), mimetype='application/javascript')
520 elif (name == "hpcUserSite"):
521 return HttpResponse(json.dumps(getUserSliceInfo(request.user, True)), mimetype='application/javascript')
522 elif (name == "hpcMap"):
523 return HttpResponse(json.dumps(getCDNOperatorData(True)), mimetype='application/javascript')
524 elif (name == "bigquery"):
525 (mimetype, data) = DoPlanetStackAnalytics(request)
526 return HttpResponse(data, mimetype=mimetype)
527 else:
528 return HttpResponse(json.dumps("Unknown"), mimetype='application/javascript')
529