blob: 2fcef2083afd17f827adcdb79bab4ba2bc9058bf [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 Baker168b7412014-05-16 14:25:41 -070010from syndicate.models import *
Scott Baker537d8232014-04-08 23:40:56 -070011from core.models import *
Scott Bakere9f4ec92014-04-29 11:29:45 -070012from hpc.models import ContentProvider
Scott Bakerbd57a432014-04-14 16:12:15 -070013from operator import attrgetter
Scott Baker186ae612014-05-19 10:42:51 -070014from django import template
Scott Bakerbd57a432014-04-14 16:12:15 -070015from django.views.decorators.csrf import csrf_exempt
Scott Baker60fd8cd2014-05-21 18:02:44 -070016from django.http import HttpResponse, HttpResponseServerError, HttpResponseForbidden
Scott Baker537d8232014-04-08 23:40:56 -070017from django.core import urlresolvers
Scott Bakerbd57a432014-04-14 16:12:15 -070018from django.contrib.gis.geoip import GeoIP
19from ipware.ip import get_ip
Scott Baker2c3cb642014-05-19 17:55:56 -070020from operator import itemgetter, attrgetter
Scott Baker771819b2014-03-19 22:10:17 -070021import traceback
Scott Baker6253dfc2014-04-14 09:29:30 -070022import socket
Siobhan Tully06d2c032014-02-23 23:48:52 -050023
Scott Bakera880bb52014-04-14 23:52:48 -070024BLESSED_SITES = ["Stanford", "Washington", "Princeton", "GeorgiaTech", "MaxPlanck"]
25
Scott Baker771819b2014-03-19 22:10:17 -070026if os.path.exists("/home/smbaker/projects/vicci/cdn/bigquery"):
27 sys.path.append("/home/smbaker/projects/vicci/cdn/bigquery")
28else:
29 sys.path.append("/opt/planetstack/hpc_wizard")
30import hpc_wizard
Scott Baker75095b62014-04-21 17:32:09 -070031from planetstack_analytics import DoPlanetStackAnalytics, PlanetStackAnalytics, RED_LOAD, BLUE_LOAD
Siobhan Tullycf04fb62014-01-11 11:25:57 -050032
33class DashboardWelcomeView(TemplateView):
34 template_name = 'admin/dashboard/welcome.html'
35
36 def get(self, request, *args, **kwargs):
37 context = self.get_context_data(**kwargs)
Scott Baker2c3cb642014-05-19 17:55:56 -070038 context = getDashboardContext(request.user, context)
Siobhan Tullycf04fb62014-01-11 11:25:57 -050039 return self.render_to_response(context=context)
Siobhan Tullye18b3442014-02-23 14:23:34 -050040
Scott Baker2c3cb642014-05-19 17:55:56 -070041class DashboardDynamicView(TemplateView):
Scott Baker186ae612014-05-19 10:42:51 -070042 head_template = r"""{% extends "admin/dashboard/dashboard_base.html" %}
43 {% load admin_static %}
44 {% block content %}
45 """
46
47 tail_template = r"{% endblock %}"
48
Scott Baker2c3cb642014-05-19 17:55:56 -070049 def get(self, request, name="root", *args, **kwargs):
Scott Baker186ae612014-05-19 10:42:51 -070050 context = self.get_context_data(**kwargs)
Scott Baker2c3cb642014-05-19 17:55:56 -070051 context = getDashboardContext(request.user, context)
Scott Baker186ae612014-05-19 10:42:51 -070052
Scott Baker2c3cb642014-05-19 17:55:56 -070053 if name=="root":
54 return self.multiDashboardView(request, context)
55 else:
56 return self.singleDashboardView(request, name, context)
57
58 def readDashboard(self, fn):
59 try:
60 template= open("/opt/planetstack/templates/admin/dashboard/%s.html" % fn, "r").read()
61 if (fn=="tenant"):
Scott Baker7237cdc2014-05-21 16:55:18 -070062 # fix for tenant view - it writes html to a div called tabs-5
Scott Baker2c3cb642014-05-19 17:55:56 -070063 template = '<div id="tabs-5"></div>' + template
Scott Baker7237cdc2014-05-21 16:55:18 -070064 if (fn=="slice_interactions"):
65 # fix for slice_interactions - it gives its container div a 40px
66 # margin, and then positions it's header at -40px
Scott Baker2de3f8f2014-05-21 16:56:58 -070067 template = '<div id="tabs-4">' + template + '</div>'
Scott Baker2c3cb642014-05-19 17:55:56 -070068 return template
69 except:
70 return "failed to open %s" % fn
71
72 def multiDashboardView(self, request, context):
Scott Bakerfc06e782014-05-19 10:52:10 -070073 head_template = self.head_template
74 tail_template = self.tail_template
75
Scott Baker2c3cb642014-05-19 17:55:56 -070076 body = """
77 <div id="hometabs" >
78 <ul id="suit_form_tabs" class="nav nav-tabs nav-tabs-suit" data-tab-prefix="suit-tab">
79 """
Scott Bakerfc06e782014-05-19 10:52:10 -070080
Scott Baker2c3cb642014-05-19 17:55:56 -070081 dashboards = request.user.get_dashboards()
Scott Bakerfc06e782014-05-19 10:52:10 -070082
Scott Baker2c3cb642014-05-19 17:55:56 -070083 # customize is a special dashboard they always get
84 customize = DashboardView.objects.filter(name="Customize")
85 if customize:
86 dashboards.append(customize[0])
Scott Baker186ae612014-05-19 10:42:51 -070087
Scott Baker2c3cb642014-05-19 17:55:56 -070088 for i,view in enumerate(dashboards):
89 body = body + '<li><a href="#dashtab-%d">%s</a></li>\n' % (i, view.name)
Scott Baker186ae612014-05-19 10:42:51 -070090
Scott Baker2c3cb642014-05-19 17:55:56 -070091 body = body + "</ul>\n"
92
93 for i,view in enumerate(dashboards):
94 url = view.url
95 body = body + '<div id="dashtab-%d">\n' % i
96 if url.startswith("template:"):
97 fn = url[9:]
98 body = body + self.readDashboard(fn)
99 body = body + '</div>\n'
100
101 body=body+"</div>\n"
102
103 t = template.Template(head_template + body + self.tail_template)
Scott Baker186ae612014-05-19 10:42:51 -0700104
105 response_kwargs = {}
106 response_kwargs.setdefault('content_type', self.content_type)
107 return self.response_class(
108 request = request,
109 template = t,
110 context = context,
111 **response_kwargs)
112
Scott Baker2c3cb642014-05-19 17:55:56 -0700113 def singleDashboardView(self, request, name, context):
114 head_template = self.head_template
115 tail_template = self.tail_template
116
117 t = template.Template(head_template + self.readDashboard(fn) + self.tail_template)
118
119 response_kwargs = {}
120 response_kwargs.setdefault('content_type', self.content_type)
121 return self.response_class(
122 request = request,
123 template = t,
124 context = context,
125 **response_kwargs)
126
127def getDashboardContext(user, context={}, tableFormat = False):
128 context = {}
Scott Baker771819b2014-03-19 22:10:17 -0700129
130 userSliceData = getSliceInfo(user)
131 if (tableFormat):
Scott Baker2c3cb642014-05-19 17:55:56 -0700132 context['userSliceInfo'] = userSliceTableFormatter(userSliceData)
Scott Baker771819b2014-03-19 22:10:17 -0700133 else:
Scott Baker2c3cb642014-05-19 17:55:56 -0700134 context['userSliceInfo'] = userSliceData
135 context['cdnData'] = getCDNOperatorData(wait=False)
136 context['cdnContentProviders'] = getCDNContentProviderData()
137
138 (dashboards, unusedDashboards)= getDashboards(user)
139 unusedDashboards=[x for x in unusedDashboards if x!="Customize"]
140 context['dashboards'] = dashboards
141 context['unusedDashboards'] = unusedDashboards
142
143 return context
144
145def getDashboards(user):
146 #dashboards = sorted(list(user.dashboardViews.all()), key=attrgetter('order'))
147 dashboards = user.get_dashboards()
148
149 dashboard_names = [d.name for d in dashboards]
150
151 unused_dashboard_names = []
152 for dashboardView in DashboardView.objects.all():
153 if not dashboardView.name in dashboard_names:
154 unused_dashboard_names.append(dashboardView.name)
155
156 return (dashboard_names, unused_dashboard_names)
Scott Baker771819b2014-03-19 22:10:17 -0700157
Scott Baker537d8232014-04-08 23:40:56 -0700158class TenantCreateSlice(View):
159 def post(self, request, *args, **kwargs):
160 sliceName = request.POST.get("sliceName", "0")
161 serviceClass = request.POST.get("serviceClass", "0")
162 imageName = request.POST.get("imageName", "0")
163 actionToDo = request.POST.get("actionToDo", "0")
Scott Baker9d9650d2014-05-23 11:50:54 -0700164 networkPorts = request.POST.get("network","0")
Scott Bakeredf2f672014-04-22 10:17:37 -0700165 mountDataSets = request.POST.get("mountDataSets","0")
Scott Baker9d9650d2014-05-23 11:50:54 -0700166 privateVolume = request.POST.get("privateVolume","0")
Scott Baker537d8232014-04-08 23:40:56 -0700167 if (actionToDo == "add"):
168 serviceClass = ServiceClass.objects.get(name=serviceClass)
169 site = request.user.site
Scott Baker4b0cedd2014-04-22 21:01:21 -0700170 image = Image.objects.get(name=imageName)
Scott Baker168b7412014-05-16 14:25:41 -0700171 newSlice = Slice(name=sliceName,serviceClass=serviceClass,site=site,imagePreference=image,mountDataSets=mountDataSets)
Scott Baker537d8232014-04-08 23:40:56 -0700172 newSlice.save()
Scott Baker9d9650d2014-05-23 11:50:54 -0700173 privateTemplate="Private"
174 publicTemplate="Public shared IPv4"
175 privateNetworkName = sliceName+"-"+privateTemplate
176 publicNetworkName = sliceName+"-"+publicTemplate
177 slice=Slice.objects.get(name=sliceName)
178 addNetwork(privateNetworkName,privateTemplate,slice)
179 addNetwork(publicNetworkName,publicTemplate,slice)
180 addOrModifyPorts(networkPorts,sliceName)
181 if privateVolume=="true":
182 privateVolForSlice(request.user,sliceName)
Scott Baker4b0cedd2014-04-22 21:01:21 -0700183 return HttpResponse("Slice created")
Scott Baker537d8232014-04-08 23:40:56 -0700184
Scott Baker9d9650d2014-05-23 11:50:54 -0700185def privateVolForSlice(user,sliceName):
186 if not hasPrivateVolume(sliceName):
187 volumeName=createPrivateVolume(user,sliceName)
188 readWrite="true"
189 mountVolume(sliceName,volumeName,readWrite)
190
Scott Bakeredf2f672014-04-22 10:17:37 -0700191class TenantUpdateSlice(View):
192 def post(self, request, *args, **kwargs):
193 sliceName = request.POST.get("sliceName", "0")
194 serviceClass = request.POST.get("serviceClass", "0")
195 imageName = request.POST.get("imageName", "0")
196 actionToDo = request.POST.get("actionToDo", "0")
Scott Baker9d9650d2014-05-23 11:50:54 -0700197 networkPorts = request.POST.get("networkPorts","0")
Scott Baker4b0cedd2014-04-22 21:01:21 -0700198 dataSet = request.POST.get("dataSet","0")
Scott Baker9d9650d2014-05-23 11:50:54 -0700199 privateVolume = request.POST.get("privateVolume","0")
Scott Baker4b0cedd2014-04-22 21:01:21 -0700200 slice = Slice.objects.all()
201 for entry in slice:
202 serviceClass = ServiceClass.objects.get(name=serviceClass)
203 if(entry.name==sliceName):
204 if (actionToDo == "update"):
205 setattr(entry,'serviceClass',serviceClass)
206 setattr(entry,'imagePreference',imageName)
Scott Baker4b0cedd2014-04-22 21:01:21 -0700207 setattr(entry,'mountDataSets',dataSet)
208 entry.save()
209 break
Scott Baker9d9650d2014-05-23 11:50:54 -0700210 addOrModifyPorts(networkPorts,sliceName)
211 if privateVolume=="true":
212 privateVolForSlice(request.user,sliceName)
Scott Baker4b0cedd2014-04-22 21:01:21 -0700213 return HttpResponse("Slice updated")
214
Scott Baker9d9650d2014-05-23 11:50:54 -0700215def addNetwork(name,template,sliceName):
216 networkTemplate=NetworkTemplate.objects.get(name=template)
217 newNetwork = Network(name = name,
218 template = networkTemplate,
219 owner = sliceName)
220 newNetwork.save()
221 addNetworkSlice(newNetwork,sliceName)
222
223def addNetworkSlice(networkSlice,sliceName):
224 newNetworkSlice=NetworkSlice(network =networkSlice,
225 slice=sliceName)
226 newNetworkSlice.save()
227
228def addOrModifyPorts(networkPorts,sliceName):
229 networkList = Network.objects.all()
230 networkInfo = []
231 if networkPorts:
232 for networkEntry in networkList:
233 networkSlices = networkEntry.slices.all()
234 for slice in networkSlices:
235 if slice.name==sliceName:
236 if networkEntry.template.name=="Public shared IPv4":
237 setattr(networkEntry,'ports',networkPorts)
238 networkEntry.save()
239
Scott Baker537d8232014-04-08 23:40:56 -0700240def getTenantSliceInfo(user, tableFormat = False):
241 tenantSliceDetails = {}
242 tenantSliceData = getTenantInfo(user)
243 tenantServiceClassData = getServiceClassInfo(user)
244 if (tableFormat):
245 tenantSliceDetails['userSliceInfo'] = userSliceTableFormatter(tenantSliceData)
246 tenantSliceDetails['sliceServiceClass']=userSliceTableFormatter(tenantServiceClassData)
247 else:
248 tenantSliceDetails['userSliceInfo'] = tenantSliceData
249 tenantSliceDetails['sliceServiceClass']=userSliceTableFormatter(tenantServiceClassData)
250 tenantSliceDetails['image']=userSliceTableFormatter(getImageInfo(user))
Scott Baker537d8232014-04-08 23:40:56 -0700251 tenantSliceDetails['deploymentSites']=userSliceTableFormatter(getDeploymentSites())
Scott Bakerb85c26b2014-04-18 11:25:32 -0700252 tenantSliceDetails['sites'] = userSliceTableFormatter(getTenantSitesInfo())
253 tenantSliceDetails['mountDataSets'] = userSliceTableFormatter(getMountDataSets())
Scott Baker168b7412014-05-16 14:25:41 -0700254 tenantSliceDetails['publicKey'] = getPublicKey(user)
Scott Baker537d8232014-04-08 23:40:56 -0700255 return tenantSliceDetails
256
Scott Baker537d8232014-04-08 23:40:56 -0700257def getTenantInfo(user):
258 slices =Slice.objects.all()
259 userSliceInfo = []
260 for entry in slices:
261 sliceName = Slice.objects.get(id=entry.id).name
262 slice = Slice.objects.get(name=Slice.objects.get(id=entry.id).name)
263 sliceServiceClass = entry.serviceClass.name
264 preferredImage = entry.imagePreference
Scott Baker9d9650d2014-05-23 11:50:54 -0700265 #sliceDataSet = entry.mountDataSets
266 sliceNetwork = {}
Scott Baker537d8232014-04-08 23:40:56 -0700267 numSliver = 0
268 sliceImage=""
269 sliceSite = {}
Scott Bakeredf2f672014-04-22 10:17:37 -0700270 sliceNode = {}
271 sliceInstance= {}
Scott Baker9d9650d2014-05-23 11:50:54 -0700272 #createPrivateVolume(user,sliceName)
Scott Baker537d8232014-04-08 23:40:56 -0700273 for sliver in slice.slivers.all():
Scott Bakera880bb52014-04-14 23:52:48 -0700274 if sliver.node.site.name in BLESSED_SITES:
Scott Bakera880bb52014-04-14 23:52:48 -0700275 sliceSite[sliver.node.site.name] = sliceSite.get(sliver.node.site.name,0) + 1
276 sliceImage = sliver.image.name
Scott Bakerb37ce332014-04-22 22:57:40 -0700277 sliceNode[str(sliver)] = sliver.node.name
Scott Bakeredf2f672014-04-22 10:17:37 -0700278 numSliver = sum(sliceSite.values())
Scott Bakerb85c26b2014-04-18 11:25:32 -0700279 numSites = len(sliceSite)
Scott Baker9d9650d2014-05-23 11:50:54 -0700280 userSliceInfo.append({'sliceName': sliceName,'sliceServiceClass': sliceServiceClass,'preferredImage':preferredImage,'numOfSites':numSites, 'sliceSite':sliceSite,'sliceImage':sliceImage,'numOfSlivers':numSliver,'instanceNodePair':sliceNode})
Scott Baker537d8232014-04-08 23:40:56 -0700281 return userSliceInfo
282
283def getTenantSitesInfo():
284 tenantSiteInfo=[]
285 for entry in Site.objects.all():
Scott Bakera880bb52014-04-14 23:52:48 -0700286 if entry.name in BLESSED_SITES:
287 tenantSiteInfo.append({'siteName':entry.name})
Scott Baker537d8232014-04-08 23:40:56 -0700288 return tenantSiteInfo
289
Scott Baker771819b2014-03-19 22:10:17 -0700290def userSliceTableFormatter(data):
291# pprint(data)
292 formattedData = {
293 'rows' : data
294 }
295 return formattedData
296
Scott Baker168b7412014-05-16 14:25:41 -0700297def getPublicKey(user):
298 users=User.objects.all()
299 for key in users:
300 if (str(key.email)==str(user)):
301 sshKey = key.public_key
302 return sshKey
303
Scott Baker537d8232014-04-08 23:40:56 -0700304def getServiceClassInfo(user):
305 serviceClassList = ServiceClass.objects.all()
306 sliceInfo = []
307 for entry in serviceClassList:
308 sliceInfo.append({'serviceClass':entry.name})
309 return sliceInfo
310
311def getImageInfo(user):
Scott Baker4b0cedd2014-04-22 21:01:21 -0700312 imageList = Image.objects.all()
313 #imageList = ['Fedora 16 LXC rev 1.3','Hadoop','MPI']
Scott Baker537d8232014-04-08 23:40:56 -0700314 imageInfo = []
315 for imageEntry in imageList:
Scott Baker4b0cedd2014-04-22 21:01:21 -0700316 imageInfo.append({'Image':imageEntry.name})
317 #imageInfo.append({'Image':imageEntry})
Scott Baker537d8232014-04-08 23:40:56 -0700318 return imageInfo
319
Scott Baker168b7412014-05-16 14:25:41 -0700320def createPrivateVolume(user, sliceName):
321 caps = Volume.CAP_READ_DATA | Volume.CAP_WRITE_DATA | Volume.CAP_HOST_DATA
322 getattr(Volume.default_gateway_caps,"read data") | \
323 getattr(Volume.default_gateway_caps,"write data") | \
324 getattr(Volume.default_gateway_caps,"host files")
325 v = Volume(name="private_" + sliceName, owner_id=user, description="private volume for %s" % sliceName, blocksize=61440, private=True, archive=False, default_gateway_caps = caps)
326 v.save()
Scott Baker9d9650d2014-05-23 11:50:54 -0700327 return v
Scott Baker168b7412014-05-16 14:25:41 -0700328
329SYNDICATE_REPLICATE_PORTNUM = 1025
330
331def get_free_port():
332 inuse={}
333 inuse[SYNDICATE_REPLICATE_PORTNUM] = True
334 for vs in VolumeSlice.objects.all():
335 inuse[vs.peer_portnum]=True
336 inuse[vs.replicate_portnum]=True
337 for network in Network.objects.all():
Scott Baker9d9650d2014-05-23 11:50:54 -0700338 if not network_ports:
339 continue
Scott Baker168b7412014-05-16 14:25:41 -0700340 network_ports = [x.strip() for x in network.ports.split(",")]
341 for network_port in network_ports:
342 try:
343 inuse[int(network_port)] = True
344 except:
345 # in case someone has put a malformed port number in the list
346 pass
347 for i in range(1025, 65535):
348 if not inuse.get(i,False):
349 return i
350 return False
351
352def mountVolume(sliceName, volumeName, readWrite):
353 slice = Slice.objects.get(name=sliceName)
354 volume = Volume.objects.get(name=volumeName)
355 # choose some unused port numbers
356 flags = Volume.CAP_READ_DATA
357 if readWrite:
358 flags = flags | Volume.CAP_WRITE_DATA
359 vs = VolumeSlice(volume_id = volume, slice_id = slice, gateway_caps=flags, peer_portnum = get_free_port(), replicate_portnum = SYNDICATE_REPLICATE_PORTNUM)
360 vs.save()
361
362def hasPrivateVolume(sliceName):
363 slice = Slice.objects.get(name=sliceName)
364 for vs in VolumeSlice.objects.filter(slice_id=slice):
365 if vs.volume_id.private:
366 return True
367 return False
368
Scott Bakerb85c26b2014-04-18 11:25:32 -0700369def getMountDataSets():
Scott Baker168b7412014-05-16 14:25:41 -0700370 dataSetInfo=[]
371 for volume in Volume.objects.all():
372 if not volume.private:
373 dataSetInfo.append({'DataSet': volume.name})
374
Scott Bakerb85c26b2014-04-18 11:25:32 -0700375 return dataSetInfo
376
Scott Baker537d8232014-04-08 23:40:56 -0700377def getDeploymentSites():
378 deploymentList = Deployment.objects.all()
379 deploymentInfo = []
380 for entry in deploymentList:
381 deploymentInfo.append({'DeploymentSite':entry.name})
382 return deploymentInfo
383
Scott Baker771819b2014-03-19 22:10:17 -0700384def getSliceInfo(user):
Siobhan Tully06d2c032014-02-23 23:48:52 -0500385 sliceList = Slice.objects.all()
Scott Baker771819b2014-03-19 22:10:17 -0700386 slicePrivs = SlicePrivilege.objects.filter(user=user)
Siobhan Tully06d2c032014-02-23 23:48:52 -0500387 userSliceInfo = []
388 for entry in slicePrivs:
Siobhan Tullye18b3442014-02-23 14:23:34 -0500389
Scott Baker771819b2014-03-19 22:10:17 -0700390 slicename = Slice.objects.get(id=entry.slice.id).name
Scott Baker537d8232014-04-08 23:40:56 -0700391 slice = Slice.objects.get(name=Slice.objects.get(id=entry.slice.id).name)
392 sliverList=Sliver.objects.all()
393 sites_used = {}
394 for sliver in slice.slivers.all():
395 #sites_used['deploymentSites'] = sliver.node.deployment.name
396 # sites_used[sliver.image.name] = sliver.image.name
397 sites_used[sliver.node.site.name] = sliver.numberCores
Scott Baker771819b2014-03-19 22:10:17 -0700398 sliceid = Slice.objects.get(id=entry.slice.id).id
Siobhan Tully06d2c032014-02-23 23:48:52 -0500399 try:
Scott Baker771819b2014-03-19 22:10:17 -0700400 sliverList = Sliver.objects.filter(slice=entry.slice.id)
401 siteList = {}
402 for x in sliverList:
403 if x.node.site not in siteList:
404 siteList[x.node.site] = 1
405 slivercount = len(sliverList)
406 sitecount = len(siteList)
Siobhan Tully06d2c032014-02-23 23:48:52 -0500407 except:
Scott Baker771819b2014-03-19 22:10:17 -0700408 traceback.print_exc()
409 slivercount = 0
410 sitecount = 0
Siobhan Tully06d2c032014-02-23 23:48:52 -0500411
Scott Baker771819b2014-03-19 22:10:17 -0700412 userSliceInfo.append({'slicename': slicename, 'sliceid':sliceid,
Scott Baker537d8232014-04-08 23:40:56 -0700413 'sitesUsed':sites_used,
414 'role': SliceRole.objects.get(id=entry.role.id).role,
415 'slivercount': slivercount,
416 'sitecount':sitecount})
Scott Baker771819b2014-03-19 22:10:17 -0700417
Siobhan Tully06d2c032014-02-23 23:48:52 -0500418 return userSliceInfo
419
Scott Bakere9f4ec92014-04-29 11:29:45 -0700420def getCDNContentProviderData():
421 cps = []
422 for dm_cp in ContentProvider.objects.all():
423 cp = {"name": dm_cp.name,
424 "account": dm_cp.account}
425 cps.append(cp)
426
427 return cps
428
Scott Baker75095b62014-04-21 17:32:09 -0700429def getCDNOperatorData(randomizeData = False, wait=True):
430 HPC_SLICE_NAME = "HyperCache"
431
Scott Baker0017c102014-04-18 10:48:31 -0700432 bq = PlanetStackAnalytics()
Siobhan Tully06d2c032014-02-23 23:48:52 -0500433
Scott Baker4a4472d2014-05-13 17:07:46 -0700434 rows = bq.get_cached_query_results(bq.compose_cached_query(), wait)
Siobhan Tully06d2c032014-02-23 23:48:52 -0500435
Scott Bakeredf2f672014-04-22 10:17:37 -0700436 # wait=False on the first time the Dashboard is opened. This means we might
437 # not have any rows yet. The dashboard code polls every 30 seconds, so it
438 # will eventually pick them up.
Scott Baker0017c102014-04-18 10:48:31 -0700439
Scott Baker75095b62014-04-21 17:32:09 -0700440 if rows:
Scott Baker696e2662014-04-24 17:03:29 -0700441 rows = bq.postprocess_results(rows, filter={"event": "hpc_heartbeat"}, maxi=["cpu"], count=["hostname"], computed=["bytes_sent/elapsed"], groupBy=["Time","site"], maxDeltaTime=80)
Scott Baker0017c102014-04-18 10:48:31 -0700442
Scott Baker75095b62014-04-21 17:32:09 -0700443 # dictionaryize the statistics rows by site name
444 stats_rows = {}
445 for row in rows:
446 stats_rows[row["site"]] = row
Scott Bakeredf2f672014-04-22 10:17:37 -0700447 else:
448 stats_rows = {}
Scott Baker0017c102014-04-18 10:48:31 -0700449
Scott Baker09fad022014-04-30 09:50:01 -0700450 slice = Slice.objects.filter(name=HPC_SLICE_NAME)
451 if slice:
452 slice_slivers = list(slice[0].slivers.all())
453 else:
454 slice_slivers = []
Scott Baker0017c102014-04-18 10:48:31 -0700455
456 new_rows = {}
Scott Baker75095b62014-04-21 17:32:09 -0700457 for site in Site.objects.all():
458 # compute number of slivers allocated in the data model
459 allocated_slivers = 0
460 for sliver in slice_slivers:
461 if sliver.node.site == site:
462 allocated_slivers = allocated_slivers + 1
463
464 stats_row = stats_rows.get(site.name,{})
465
466 max_cpu = stats_row.get("max_avg_cpu", stats_row.get("max_cpu",0))
467 cpu=float(max_cpu)/100.0
468 hotness = max(0.0, ((cpu*RED_LOAD) - BLUE_LOAD)/(RED_LOAD-BLUE_LOAD))
469
470 # format it to what that CDN Operations View is expecting
471 new_row = {"lat": float(site.location.longitude),
472 "long": float(site.location.longitude),
473 "lat": float(site.location.latitude),
Scott Baker0017c102014-04-18 10:48:31 -0700474 "health": 0,
Scott Baker75095b62014-04-21 17:32:09 -0700475 "numNodes": int(site.nodes.count()),
Scott Bakere9f4ec92014-04-29 11:29:45 -0700476 "activeHPCSlivers": int(stats_row.get("count_hostname", 0)), # measured number of slivers, from bigquery statistics
Scott Baker75095b62014-04-21 17:32:09 -0700477 "numHPCSlivers": allocated_slivers, # allocated number of slivers, from data model
478 "siteUrl": str(site.site_url),
479 "bandwidth": stats_row.get("sum_computed_bytes_sent_div_elapsed",0),
480 "load": max_cpu,
481 "hot": float(hotness)}
482 new_rows[str(site.name)] = new_row
483
484 # get rid of sites with 0 slivers that overlap other sites with >0 slivers
485 for (k,v) in new_rows.items():
486 bad=False
487 if v["numHPCSlivers"]==0:
488 for v2 in new_rows.values():
489 if (v!=v2) and (v2["numHPCSlivers"]>=0):
490 d = haversine(v["lat"],v["long"],v2["lat"],v2["long"])
491 if d<100:
492 bad=True
493 if bad:
494 del new_rows[k]
Scott Baker0017c102014-04-18 10:48:31 -0700495
496 return new_rows
Siobhan Tully06d2c032014-02-23 23:48:52 -0500497
Scott Baker168b7412014-05-16 14:25:41 -0700498def getPageSummary(request):
499 slice = request.GET.get('slice', None)
500 site = request.GET.get('site', None)
501 node = request.GET.get('node', None)
502
Scott Baker771819b2014-03-19 22:10:17 -0700503class SimulatorView(View):
504 def get(self, request, **kwargs):
505 sim = json.loads(file("/tmp/simulator.json","r").read())
506 text = "<html><head></head><body>"
507 text += "Iteration: %d<br>" % sim["iteration"]
508 text += "Elapsed since report %d<br><br>" % sim["elapsed_since_report"]
509 text += "<table border=1>"
510 text += "<tr><th>site</th><th>trend</th><th>weight</th><th>bytes_sent</th><th>hot</th></tr>"
511 for site in sim["site_load"].values():
512 text += "<tr>"
513 text += "<td>%s</td><td>%0.2f</td><td>%0.2f</td><td>%d</td><td>%0.2f</td>" % \
514 (site["name"], site["trend"], site["weight"], site["bytes_sent"], site["load_frac"])
515 text += "</tr>"
516 text += "</table>"
517 text += "</body></html>"
518 return HttpResponse(text)
519
520class DashboardUserSiteView(View):
521 def get(self, request, **kwargs):
Scott Baker2c3cb642014-05-19 17:55:56 -0700522 return HttpResponse(json.dumps(getDashboardContext(request.user, tableFormat=True)), mimetype='application/javascript')
Scott Baker771819b2014-03-19 22:10:17 -0700523
Scott Baker537d8232014-04-08 23:40:56 -0700524class TenantViewData(View):
525 def get(self, request, **kwargs):
526 return HttpResponse(json.dumps(getTenantSliceInfo(request.user, True)), mimetype='application/javascript')
527
Scott Baker75095b62014-04-21 17:32:09 -0700528def haversine(site_lat, site_lon, lat, lon):
Scott Baker75095b62014-04-21 17:32:09 -0700529 d=0
530 if lat and lon and site_lat and site_lon:
Scott Baker4b0cedd2014-04-22 21:01:21 -0700531 site_lat = float(site_lat)
532 site_lon = float(site_lon)
533 lat = float(lat)
534 lon = float(lon)
Scott Baker75095b62014-04-21 17:32:09 -0700535 R = 6378.1
536 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)
537 c = 2 * math.atan2( math.sqrt(a), math.sqrt(1 - a) )
538 d = R * c
539
540 return d
541
Scott Bakerbd57a432014-04-14 16:12:15 -0700542def siteSortKey(site, slice=None, count=None, lat=None, lon=None):
543 # try to pick a site we're already using
544 has_slivers_here=False
545 if slice:
546 for sliver in slice.slivers.all():
547 if sliver.node.site.name == site.name:
548 has_slivers_here=True
549
550 # Haversine method
Scott Baker75095b62014-04-21 17:32:09 -0700551 d = haversine(site.location.latitude, site.location.longitude, lat, lon)
Scott Bakerbd57a432014-04-14 16:12:15 -0700552
553 return (-has_slivers_here, d)
554
555def tenant_pick_sites(user, user_ip=None, slice=None, count=None):
556 """ Returns list of sites, sorted from most favorable to least favorable """
557 lat=None
558 lon=None
559 try:
560 client_geo = GeoIP().city(user_ip)
561 if client_geo:
562 lat=float(client_geo["latitude"])
563 lon=float(client_geo["longitude"])
564 except:
565 print "exception in geo code"
566 traceback.print_exc()
567
568 sites = Site.objects.all()
Scott Bakera880bb52014-04-14 23:52:48 -0700569 sites = [x for x in sites if x.name in BLESSED_SITES]
Scott Bakerbd57a432014-04-14 16:12:15 -0700570 sites = sorted(sites, key=functools.partial(siteSortKey, slice=slice, count=count, lat=lat, lon=lon))
571
572 return sites
573
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700574def slice_increase_slivers(user, user_ip, siteList, slice, count, noAct=False):
Scott Bakere4deddd2014-04-14 16:48:05 -0700575 sitesChanged = {}
576
Scott Bakerbd57a432014-04-14 16:12:15 -0700577 # let's compute how many slivers are in use in each node of each site
578 for site in siteList:
579 site.nodeList = list(site.nodes.all())
580 for node in site.nodeList:
581 node.sliverCount = 0
Scott Baker6253dfc2014-04-14 09:29:30 -0700582 for sliver in node.slivers.all():
Scott Baker21511942014-04-15 17:44:27 -0700583 if sliver.slice.id == slice.id:
Scott Baker0017c102014-04-18 10:48:31 -0700584 node.sliverCount = node.sliverCount + 1
Scott Baker6253dfc2014-04-14 09:29:30 -0700585
Scott Bakerbd57a432014-04-14 16:12:15 -0700586 # Allocate slivers to nodes
587 # for now, assume we want to allocate all slivers from the same site
588 nodes = siteList[0].nodeList
589 while (count>0):
590 # Sort the node list by number of slivers per node, then pick the
591 # node with the least number of slivers.
592 nodes = sorted(nodes, key=attrgetter("sliverCount"))
593 node = nodes[0]
Scott Baker6253dfc2014-04-14 09:29:30 -0700594
Scott Bakerbd57a432014-04-14 16:12:15 -0700595 print "adding sliver at node", node.name, "of site", node.site.name
Scott Baker6253dfc2014-04-14 09:29:30 -0700596
Scott Bakere4deddd2014-04-14 16:48:05 -0700597 if not noAct:
598 sliver = Sliver(name=node.name,
599 slice=slice,
600 node=node,
601 image = Image.objects.all()[0],
602 creator = User.objects.get(email=user),
603 deploymentNetwork=node.deployment,
604 numberCores =1 )
605 sliver.save()
Scott Bakerbd57a432014-04-14 16:12:15 -0700606
607 node.sliverCount = node.sliverCount + 1
608
609 count = count - 1
610
Scott Bakere4deddd2014-04-14 16:48:05 -0700611 sitesChanged[node.site.name] = sitesChanged.get(node.site.name,0) + 1
612
613 return sitesChanged
614
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700615def slice_decrease_slivers(user, siteList, slice, count, noAct=False):
Scott Bakere4deddd2014-04-14 16:48:05 -0700616 sitesChanged = {}
Scott Bakerb85c26b2014-04-18 11:25:32 -0700617 sliverList ={}
Scott Bakerbd57a432014-04-14 16:12:15 -0700618 if siteList:
619 siteNames = [site.name for site in siteList]
620 else:
621 siteNames = None
622
623 for sliver in slice.slivers.all():
Scott Bakerb85c26b2014-04-18 11:25:32 -0700624 if(not siteNames) or (sliver.node.site.name in siteNames):
625 node = sliver.node
626 sliverList[sliver.name]=node.name
Scott Bakerbd57a432014-04-14 16:12:15 -0700627
Scott Bakerb85c26b2014-04-18 11:25:32 -0700628 for key in sliverList:
629 if count>0:
Scott Bakerf1b65c02014-04-21 01:03:17 -0700630 sliver = Sliver.objects.filter(name=key)[0]
Scott Bakerb85c26b2014-04-18 11:25:32 -0700631 sliver.delete()
632 print "deleting sliver",sliverList[key],"at node",sliver.node.name
633 count=count-1
Scott Bakerf1b65c02014-04-21 01:03:17 -0700634 sitesChanged[sliver.node.site.name] = sitesChanged.get(sliver.node.site.name,0) - 1
Scott Bakerb85c26b2014-04-18 11:25:32 -0700635
Scott Bakere4deddd2014-04-14 16:48:05 -0700636 return sitesChanged
637
Scott Bakerb85c26b2014-04-18 11:25:32 -0700638class TenantDeleteSliceView(View):
639 def post(self,request):
640 sliceName = request.POST.get("sliceName",None)
641 slice = Slice.objects.get(name=sliceName)
Scott Baker168b7412014-05-16 14:25:41 -0700642 #print slice, slice.id
Scott Bakerb85c26b2014-04-18 11:25:32 -0700643 sliceToDel=Slice(name=sliceName, id=slice.id)
644 sliceToDel.delete()
Scott Baker4b0cedd2014-04-22 21:01:21 -0700645 return HttpResponse("Slice deleted")
Scott Bakerb85c26b2014-04-18 11:25:32 -0700646
Scott Baker6253dfc2014-04-14 09:29:30 -0700647class TenantAddOrRemoveSliverView(View):
Scott Bakere4deddd2014-04-14 16:48:05 -0700648 """ Add or remove slivers from a Slice
649
650 Arguments:
651 siteName - name of site. If not specified, PlanetStack will pick the
652 best site.,
653 actionToDo - [add | rem]
654 count - number of slivers to add or remove
655 sliceName - name of slice
Scott Bakera880bb52014-04-14 23:52:48 -0700656 noAct - if set, no changes will be made to db, but result will still
657 show which sites would have been modified.
Scott Bakere4deddd2014-04-14 16:48:05 -0700658
659 Returns:
660 Dictionary of sites that were modified, and the count of nodes
661 that were added or removed at each site.
662 """
Scott Baker6253dfc2014-04-14 09:29:30 -0700663 def post(self, request, *args, **kwargs):
Scott Bakerbd57a432014-04-14 16:12:15 -0700664 siteName = request.POST.get("siteName", None)
665 actionToDo = request.POST.get("actionToDo", None)
666 count = int(request.POST.get("count","0"))
667 sliceName = request.POST.get("slice", None)
Scott Bakere4deddd2014-04-14 16:48:05 -0700668 noAct = request.POST.get("noAct", False)
Scott Bakerbd57a432014-04-14 16:12:15 -0700669
670 if not sliceName:
671 return HttpResponseServerError("No slice name given")
672
673 slice = Slice.objects.get(name=sliceName)
674
675 if siteName:
676 siteList = [Site.objects.get(name=siteName)]
677 else:
678 siteList = None
Scott Baker6253dfc2014-04-14 09:29:30 -0700679
680 if (actionToDo == "add"):
Scott Bakerbd57a432014-04-14 16:12:15 -0700681 user_ip = request.GET.get("ip", get_ip(request))
682 if (siteList is None):
683 siteList = tenant_pick_sites(user, user_ip, slice, count)
684
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700685 sitesChanged = slice_increase_slivers(request.user, user_ip, siteList, slice, count, noAct)
Scott Baker6253dfc2014-04-14 09:29:30 -0700686 elif (actionToDo == "rem"):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700687 sitesChanged = slice_decrease_slivers(request.user, siteList, slice, count, noAct)
Scott Bakerbd57a432014-04-14 16:12:15 -0700688 else:
689 return HttpResponseServerError("Unknown actionToDo %s" % actionToDo)
690
Scott Bakere4deddd2014-04-14 16:48:05 -0700691 return HttpResponse(json.dumps(sitesChanged), mimetype='application/javascript')
Scott Bakerbd57a432014-04-14 16:12:15 -0700692
693 def get(self, request, *args, **kwargs):
694 request.POST = request.GET
695 return self.post(request, *args, **kwargs) # for testing REST in browser
696 #return HttpResponseServerError("GET is not supported")
697
698class TenantPickSitesView(View):
699 """ primarily just for testing purposes """
700 def get(self, request, *args, **kwargs):
701 count = request.GET.get("count","0")
702 slice = request.GET.get("slice",None)
703 if slice:
704 slice = Slice.objects.get(name=slice)
705 ip = request.GET.get("ip", get_ip(request))
706 sites = tenant_pick_sites(request.user, user_ip=ip, count=0, slice=slice)
707 sites = [x.name for x in sites]
708 return HttpResponse(json.dumps(sites), mimetype='application/javascript')
Scott Baker6253dfc2014-04-14 09:29:30 -0700709
Scott Baker771819b2014-03-19 22:10:17 -0700710class DashboardSummaryAjaxView(View):
711 def get(self, request, **kwargs):
Scott Baker0017c102014-04-18 10:48:31 -0700712 def avg(x):
Scott Baker111702b2014-05-15 16:17:16 -0700713 if len(x)==0:
714 return 0
Scott Baker0017c102014-04-18 10:48:31 -0700715 return float(sum(x))/len(x)
716
717 sites = getCDNOperatorData().values()
718
719 sites = [site for site in sites if site["numHPCSlivers"]>0]
720
721 total_slivers = sum( [site["numHPCSlivers"] for site in sites] )
722 total_bandwidth = sum( [site["bandwidth"] for site in sites] )
723 average_cpu = int(avg( [site["load"] for site in sites] ))
724
725 result= {"total_slivers": total_slivers,
726 "total_bandwidth": total_bandwidth,
727 "average_cpu": average_cpu}
728
729 return HttpResponse(json.dumps(result), mimetype='application/javascript')
Scott Baker771819b2014-03-19 22:10:17 -0700730
731class DashboardAddOrRemoveSliverView(View):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700732 # TODO: deprecate this view in favor of using TenantAddOrRemoveSliverView
733
Scott Baker771819b2014-03-19 22:10:17 -0700734 def post(self, request, *args, **kwargs):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700735 siteName = request.POST.get("site", None)
Scott Baker771819b2014-03-19 22:10:17 -0700736 actionToDo = request.POST.get("actionToDo", "0")
737
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700738 siteList = [Site.objects.get(name=siteName)]
739 slice = Slice.objects.get(name="HyperCache")
740
Scott Bakerd927d662014-05-22 09:29:06 -0700741 if request.user.isReadOnlyUser():
742 return HttpResponseForbidden("User is in read-only mode")
743
Scott Baker771819b2014-03-19 22:10:17 -0700744 if (actionToDo == "add"):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700745 user_ip = request.GET.get("ip", get_ip(request))
746 slice_increase_slivers(request.user, user_ip, siteList, slice, 1)
Scott Baker771819b2014-03-19 22:10:17 -0700747 elif (actionToDo == "rem"):
Scott Bakerfe6a7e12014-04-15 10:58:31 -0700748 slice_decrease_slivers(request.user, siteList, slice, 1)
Scott Baker771819b2014-03-19 22:10:17 -0700749
750 print '*' * 50
751 print 'Ask for site: ' + siteName + ' to ' + actionToDo + ' another HPC Sliver'
Scott Bakerd927d662014-05-22 09:29:06 -0700752 return HttpResponse(json.dumps("Success"), mimetype='application/javascript')
Siobhan Tully06d2c032014-02-23 23:48:52 -0500753
754class DashboardAjaxView(View):
755 def get(self, request, **kwargs):
756 return HttpResponse(json.dumps(getCDNOperatorData(True)), mimetype='application/javascript')
Scott Baker771819b2014-03-19 22:10:17 -0700757
758class DashboardAnalyticsAjaxView(View):
759 def get(self, request, name="hello_world", **kwargs):
760 if (name == "hpcSummary"):
761 return HttpResponse(json.dumps(hpc_wizard.get_hpc_wizard().get_summary_for_view()), mimetype='application/javascript')
762 elif (name == "hpcUserSite"):
Scott Baker2c3cb642014-05-19 17:55:56 -0700763 return HttpResponse(json.dumps(getDashboardContext(request.user, tableFormat=True)), mimetype='application/javascript')
Scott Baker771819b2014-03-19 22:10:17 -0700764 elif (name == "hpcMap"):
765 return HttpResponse(json.dumps(getCDNOperatorData(True)), mimetype='application/javascript')
766 elif (name == "bigquery"):
767 (mimetype, data) = DoPlanetStackAnalytics(request)
768 return HttpResponse(data, mimetype=mimetype)
769 else:
770 return HttpResponse(json.dumps("Unknown"), mimetype='application/javascript')
771
Scott Baker2c3cb642014-05-19 17:55:56 -0700772class DashboardCustomize(View):
773 def post(self, request, *args, **kwargs):
Scott Baker60fd8cd2014-05-21 18:02:44 -0700774 if request.user.isReadOnlyUser():
775 return HttpResponseForbidden("User is in read-only mode")
776
Scott Baker2c3cb642014-05-19 17:55:56 -0700777 dashboards = request.POST.get("dashboards", None)
778 if not dashboards:
Scott Baker2870e272014-05-19 18:14:54 -0700779 dashboards=[]
780 else:
781 dashboards = [x.strip() for x in dashboards.split(",")]
782 dashboards = [DashboardView.objects.get(name=x) for x in dashboards]
Scott Baker2c3cb642014-05-19 17:55:56 -0700783
784 request.user.dashboardViews.all().delete()
785
786 for i,dashboard in enumerate(dashboards):
787 udbv = UserDashboardView(user=request.user, dashboardView=dashboard, order=i)
788 udbv.save()
789
Scott Baker60fd8cd2014-05-21 18:02:44 -0700790 return HttpResponse(json.dumps("Success"), mimetype='application/javascript')
Scott Baker2c3cb642014-05-19 17:55:56 -0700791