blob: 8fee0dc014c30f42169e7fa101f03af5339bebae [file] [log] [blame]
Scott Baker43adf1b2014-03-19 21:54:55 -07001from bigquery_analytics import BigQueryAnalytics
Scott Baker050b1b82014-03-27 09:13:41 -07002import datetime
3import re
Scott Bakerc527fda2014-03-20 17:14:52 -07004import os
5import sys
Scott Baker95b28d62014-04-18 10:45:26 -07006import time
Scott Baker43adf1b2014-03-19 21:54:55 -07007import json
Scott Baker78ab1012014-03-19 23:44:39 -07008import traceback
Scott Baker050b1b82014-03-27 09:13:41 -07009import urllib2
Scott Baker43adf1b2014-03-19 21:54:55 -070010
Scott Bakerc527fda2014-03-20 17:14:52 -070011if os.path.exists("/home/smbaker/projects/vicci/plstackapi/planetstack"):
12 sys.path.append("/home/smbaker/projects/vicci/plstackapi/planetstack")
13else:
14 sys.path.append("/opt/planetstack")
15
16os.environ.setdefault("DJANGO_SETTINGS_MODULE", "planetstack.settings")
17from django import db
18from django.db import connection
19from core.models import Slice, Sliver, ServiceClass, Reservation, Tag, Network, User, Node, Image, Deployment, Site, NetworkTemplate, NetworkSlice, Service
20
21BLUE_LOAD=5000000
22RED_LOAD=15000000
23
Scott Baker95b28d62014-04-18 10:45:26 -070024glo_cached_queries = {}
25
Scott Baker43adf1b2014-03-19 21:54:55 -070026class PlanetStackAnalytics(BigQueryAnalytics):
27 def __init__(self, tableName="demoevents"):
28 BigQueryAnalytics.__init__(self, tableName)
29
Scott Bakerc527fda2014-03-20 17:14:52 -070030 def service_to_sliceNames(self, serviceName):
31 service=Service.objects.get(name=serviceName)
32 try:
33 slices = service.slices.all()
34 except:
35 # BUG in data model -- Slice.service has related name 'service' and
36 # it should be 'slices'
37 slices = service.service.all()
38
39 return [slice.name for slice in slices]
40
Scott Baker95b28d62014-04-18 10:45:26 -070041 def compose_query(self, slice=None, site=None, node=None, service=None, timeBucket="60", avg=[], sum=[], count=[], computed=[], val=[], groupBy=["Time"], orderBy=["Time"], tableName="demoevents", latest=False):
42 tablePart = "[%s.%s@-3600000--1]" % ("vicci", tableName)
Scott Baker43adf1b2014-03-19 21:54:55 -070043
44 fields = []
45 fieldNames = []
Scott Baker95b28d62014-04-18 10:45:26 -070046 srcFieldNames = ["time"]
Scott Baker43adf1b2014-03-19 21:54:55 -070047
Scott Baker050b1b82014-03-27 09:13:41 -070048 fields.append("SEC_TO_TIMESTAMP(INTEGER(TIMESTAMP_TO_SEC(time)/%s)*%s) as Time" % (str(timeBucket),str(timeBucket)))
49 #fields.append("INTEGER(TIMESTAMP_TO_SEC(time)/%s)*%s as Time" % (str(timeBucket),str(timeBucket)))
Scott Baker43adf1b2014-03-19 21:54:55 -070050
51 for fieldName in avg:
52 fields.append("AVG(%s) as avg_%s" % (fieldName, fieldName.replace("%","")))
53 fieldNames.append("avg_%s" % fieldName.replace("%",""))
Scott Baker95b28d62014-04-18 10:45:26 -070054 srcFieldNames.append(fieldName)
Scott Baker43adf1b2014-03-19 21:54:55 -070055
56 for fieldName in sum:
57 fields.append("SUM(%s) as sum_%s" % (fieldName, fieldName.replace("%","")))
58 fieldNames.append("sum_%s" % fieldName.replace("%",""))
Scott Baker95b28d62014-04-18 10:45:26 -070059 srcFieldNames.append(fieldName)
Scott Baker43adf1b2014-03-19 21:54:55 -070060
61 for fieldName in count:
62 fields.append("COUNT(distinct %s) as count_%s" % (fieldName, fieldName.replace("%","")))
63 fieldNames.append("count_%s" % fieldName.replace("%",""))
Scott Baker95b28d62014-04-18 10:45:26 -070064 srcFieldNames.append(fieldName)
65
66 for fieldName in val:
67 fields.append(fieldName)
68 fieldNames.append(fieldName)
69 srcFieldNames.append(fieldName)
Scott Baker43adf1b2014-03-19 21:54:55 -070070
71 for fieldName in computed:
72 operator = "/"
73 parts = fieldName.split("/")
74 computedFieldName = "computed_" + parts[0].replace("%","")+"_div_"+parts[1].replace("%","")
75 if len(parts)==1:
76 operator = "*"
77 parts = computed.split("*")
78 computedFieldName = "computed_" + parts[0].replace("%","")+"_mult_"+parts[1].replace("%","")
79 fields.append("SUM(%s)%sSUM(%s) as %s" % (parts[0], operator, parts[1], computedFieldName))
80 fieldNames.append(computedFieldName)
Scott Baker95b28d62014-04-18 10:45:26 -070081 srcFieldNames.append(parts[0])
82 srcFieldNames.append(parts[1])
Scott Baker43adf1b2014-03-19 21:54:55 -070083
Scott Bakerc527fda2014-03-20 17:14:52 -070084 for fieldName in groupBy:
Scott Baker050b1b82014-03-27 09:13:41 -070085 if (fieldName not in ["Time"]):
Scott Bakerc527fda2014-03-20 17:14:52 -070086 fields.append(fieldName)
87 fieldNames.append(fieldName)
Scott Baker95b28d62014-04-18 10:45:26 -070088 srcFieldNames.append(fieldName)
Scott Bakerc527fda2014-03-20 17:14:52 -070089
Scott Baker43adf1b2014-03-19 21:54:55 -070090 fields = ", ".join(fields)
91
92 where = []
93
94 if slice:
95 where.append("%%slice='%s'" % slice)
96 if site:
97 where.append("%%site='%s'" % site)
98 if node:
99 where.append("%%hostname='%s'" % node)
Scott Bakerc527fda2014-03-20 17:14:52 -0700100 if service:
101 sliceNames = self.service_to_sliceNames(service)
102 if sliceNames:
103 where.append("(" + " OR ".join(["%%slice='%s'" % sliceName for sliceName in sliceNames]) +")")
Scott Baker43adf1b2014-03-19 21:54:55 -0700104
105 if where:
106 where = " WHERE " + " AND ".join(where)
107 else:
108 where =""
109
110 if groupBy:
Scott Bakerc527fda2014-03-20 17:14:52 -0700111 groupBySub = " GROUP BY " + ",".join(groupBy + ["%hostname"])
Scott Baker43adf1b2014-03-19 21:54:55 -0700112 groupBy = " GROUP BY " + ",".join(groupBy)
113 else:
Scott Bakerc527fda2014-03-20 17:14:52 -0700114 groupBySub = " GROUP BY %hostname"
Scott Baker43adf1b2014-03-19 21:54:55 -0700115 groupBy = ""
116
117 if orderBy:
118 orderBy = " ORDER BY " + ",".join(orderBy)
119 else:
120 orderBy = ""
121
Scott Baker95b28d62014-04-18 10:45:26 -0700122 if latest:
123 latestFields = ["table1.%s as %s" % (x,x) for x in srcFieldNames]
124 latestFields = ", ".join(latestFields)
125 tablePart = """(SELECT %s FROM %s AS table1
126 JOIN
127 (SELECT %%hostname, event, max(time) as maxtime from %s GROUP BY %%hostname, event) AS latest
128 ON
129 table1.%%hostname = latest.%%hostname AND table1.event = latest.event AND table1.time = latest.maxtime)""" % (latestFields, tablePart, tablePart)
130
Scott Baker43adf1b2014-03-19 21:54:55 -0700131 if computed:
Scott Baker95b28d62014-04-18 10:45:26 -0700132 subQuery = "SELECT %%hostname, %s FROM %s" % (fields, tablePart)
Scott Baker43adf1b2014-03-19 21:54:55 -0700133 if where:
134 subQuery = subQuery + where
Scott Bakerc527fda2014-03-20 17:14:52 -0700135 subQuery = subQuery + groupBySub
Scott Baker43adf1b2014-03-19 21:54:55 -0700136
137 sumFields = []
138 for fieldName in fieldNames:
139 if fieldName.startswith("avg"):
140 sumFields.append("AVG(%s) as avg_%s"%(fieldName,fieldName))
Scott Bakerc527fda2014-03-20 17:14:52 -0700141 sumFields.append("MAX(%s) as max_%s"%(fieldName,fieldName))
142 elif (fieldName.startswith("count")) or (fieldName.startswith("sum")) or (fieldName.startswith("computed")):
Scott Baker43adf1b2014-03-19 21:54:55 -0700143 sumFields.append("SUM(%s) as sum_%s"%(fieldName,fieldName))
Scott Bakerc527fda2014-03-20 17:14:52 -0700144 else:
145 sumFields.append(fieldName)
Scott Baker43adf1b2014-03-19 21:54:55 -0700146
147 sumFields = ",".join(sumFields)
148
Scott Baker050b1b82014-03-27 09:13:41 -0700149 query = "SELECT %s, %s FROM (%s)" % ("Time", sumFields, subQuery)
Scott Baker43adf1b2014-03-19 21:54:55 -0700150 if groupBy:
151 query = query + groupBy
152 if orderBy:
153 query = query + orderBy
154 else:
Scott Baker95b28d62014-04-18 10:45:26 -0700155 query = "SELECT %s FROM %s" % (fields, tablePart)
Scott Baker43adf1b2014-03-19 21:54:55 -0700156 if where:
157 query = query + " " + where
158 if groupBy:
159 query = query + groupBy
160 if orderBy:
161 query = query + orderBy
162
163 return query
164
165 def get_list_from_req(self, req, name, default=[]):
166 value = req.GET.get(name, None)
167 if not value:
168 return default
Scott Baker050b1b82014-03-27 09:13:41 -0700169 value=value.replace("@","%")
Scott Baker43adf1b2014-03-19 21:54:55 -0700170 return value.split(",")
171
Scott Baker050b1b82014-03-27 09:13:41 -0700172 def format_result(self, format, result, query, dataSourceUrl):
Scott Baker43adf1b2014-03-19 21:54:55 -0700173 if (format == "json_dicts"):
Scott Baker050b1b82014-03-27 09:13:41 -0700174 result = {"query": query, "rows": result, "dataSourceUrl": dataSourceUrl}
Scott Baker43adf1b2014-03-19 21:54:55 -0700175 return ("application/javascript", json.dumps(result))
176
177 elif (format == "json_arrays"):
178 new_result = []
179 for row in result:
180 new_row = []
181 for key in sorted(row.keys()):
182 new_row.append(row[key])
183 new_result.append(new_row)
184 new_result = {"query": query, "rows": new_result}
185 return ("application/javascript", json.dumps(new_result))
186
187 elif (format == "html_table"):
188 new_rows = []
189 for row in result:
190 new_row = []
191 for key in sorted(row.keys()):
192 new_row.append("<TD>%s</TD>" % str(row[key]))
193 new_rows.append("<TR>%s</TR>" % "".join(new_row))
194
195 new_result = "<TABLE>%s</TABLE>" % "\n".join(new_rows)
196
197 return ("text/html", new_result)
198
Scott Bakerc527fda2014-03-20 17:14:52 -0700199 def merge_datamodel_sites(self, rows):
200 """ For a query that included "site" in its groupby, merge in the
201 opencloud site information.
202 """
203 for row in rows:
204 sitename = row["site"]
205 try:
206 model_site = Site.objects.get(name=sitename)
207 except:
208 # we didn't find it in the data model
209 continue
210
211 row["lat"] = float(model_site.location.latitude)
212 row["long"] = float(model_site.location.longitude)
213 row["url"] = model_site.site_url
214 row["numNodes"] = model_site.nodes.count()
215
Scott Baker95b28d62014-04-18 10:45:26 -0700216 max_cpu = row.get("max_avg_cpu", row.get("max_cpu",0))
217 cpu=float(max_cpu)/100.0
218 row["hotness"] = max(0.0, ((cpu*RED_LOAD) - BLUE_LOAD)/(RED_LOAD-BLUE_LOAD))
219
220 def compose_latest_query(self, fieldNames=None, groupByFields=["%hostname", "event"]):
221 """ Compose a query that returns the 'most recent' row for each (hostname, event)
222 pair.
223 """
224
225 if not fieldNames:
226 fieldNames = ["%hostname", "%bytes_sent", "time", "event", "%site", "%elapsed", "%slice", "%cpu"]
227
228 fields = ["table1.%s AS %s" % (x,x) for x in fieldNames]
229 fields = ", ".join(fields)
230
231 tableDesc = "%s.%s" % (self.projectName, self.tableName)
232
233 groupByOn = ["table1.time = latest.maxtime"]
234 for field in groupByFields:
235 groupByOn.append("table1.%s = latest.%s" % (field, field))
236
237 groupByOn = " AND ".join(groupByOn)
238 groupByFields = ", ".join(groupByFields)
239
240 base_query = "SELECT %s FROM [%s@-3600000--1] AS table1 JOIN (SELECT %s, max(time) as maxtime from [%s@-3600000--1] GROUP BY %s) AS latest ON %s" % \
241 (fields, tableDesc, groupByFields, tableDesc, groupByFields, groupByOn)
242
243 return base_query
244
245 def get_cached_query_results(self, q):
246 global glo_cached_queries
247
248 if q in glo_cached_queries:
249 if (time.time() - glo_cached_queries[q]["time"]) <= 60:
250 print "using cached query"
251 return glo_cached_queries[q]["rows"]
252
253 print "refreshing cached query"
254 result = self.run_query(q)
255 glo_cached_queries[q] = {"time": time.time(), "rows": result}
256
257 return result
Scott Bakerc527fda2014-03-20 17:14:52 -0700258
Scott Baker43adf1b2014-03-19 21:54:55 -0700259 def process_request(self, req):
260 print req.GET
261
Scott Baker050b1b82014-03-27 09:13:41 -0700262 tqx = req.GET.get("tqx", None)
Scott Baker43adf1b2014-03-19 21:54:55 -0700263
264 slice = req.GET.get("slice", None)
265 site = req.GET.get("site", None)
266 node = req.GET.get("node", None)
Scott Bakerc527fda2014-03-20 17:14:52 -0700267 service = req.GET.get("service", None)
Scott Baker43adf1b2014-03-19 21:54:55 -0700268
269 format = req.GET.get("format", "json_dicts")
270
Scott Baker050b1b82014-03-27 09:13:41 -0700271 timeField = req.GET.get("timeBucket", "60")
Scott Baker43adf1b2014-03-19 21:54:55 -0700272 avg = self.get_list_from_req(req, "avg")
273 sum = self.get_list_from_req(req, "sum")
274 count = self.get_list_from_req(req, "count")
275 computed = self.get_list_from_req(req, "computed")
Scott Baker050b1b82014-03-27 09:13:41 -0700276 groupBy = self.get_list_from_req(req, "groupBy", ["Time"])
277 orderBy = self.get_list_from_req(req, "orderBy", ["Time"])
Scott Baker43adf1b2014-03-19 21:54:55 -0700278
279 maxRows = req.GET.get("maxRows", None)
Scott Bakerc527fda2014-03-20 17:14:52 -0700280 mergeDataModelSites = req.GET.get("mergeDataModelSites", None)
Scott Baker43adf1b2014-03-19 21:54:55 -0700281
Scott Baker95b28d62014-04-18 10:45:26 -0700282 cached = req.GET.get("cached", None)
283
284 q = self.compose_query(slice, site, node, service, timeField, avg, sum, count, computed, [], groupBy, orderBy)
Scott Baker43adf1b2014-03-19 21:54:55 -0700285
286 print q
Scott Baker95b28d62014-04-18 10:45:26 -0700287
Scott Baker050b1b82014-03-27 09:13:41 -0700288 dataSourceUrl = "http://" + req.META["SERVER_NAME"] + ":" + req.META["SERVER_PORT"] + req.META["PATH_INFO"] + "?" + req.META["QUERY_STRING"].replace("format=","origFormat=").replace("%","%25") + "&format=charts";
Scott Baker43adf1b2014-03-19 21:54:55 -0700289
Scott Baker050b1b82014-03-27 09:13:41 -0700290 if (format=="dataSourceUrl"):
291 result = {"dataSourceUrl": dataSourceUrl}
292 return ("application/javascript", result)
293
294 elif (format=="raw"):
Scott Baker43adf1b2014-03-19 21:54:55 -0700295 result = self.run_query_raw(q)
Scott Baker050b1b82014-03-27 09:13:41 -0700296 result["dataSourceUrl"] = dataSourceUrl
297
298 result = json.dumps(result);
299
300 return ("application/javascript", result)
301
Scott Baker95b28d62014-04-18 10:45:26 -0700302 elif (format=="nodata"):
303 result = {"dataSourceUrl": dataSourceUrl, "query": q}
304 result = json.dumps(result);
305 return {"application/javascript", result}
306
Scott Baker050b1b82014-03-27 09:13:41 -0700307 elif (format=="charts"):
308 bq_result = self.run_query_raw(q)
309
310 # cloudscrutiny code is probably better!
311 table = {}
312 table["cols"] = self.schema_to_cols(bq_result["schema"])
313 rows = []
314 for row in bq_result["rows"]:
315 rowcols = []
316 for (colnum,col) in enumerate(row["f"]):
317 if (colnum==0):
318 dt = datetime.datetime.fromtimestamp(float(col["v"]))
319 rowcols.append({"v": 'new Date("%s")' % dt.isoformat()})
320 else:
321 try:
322 rowcols.append({"v": float(col["v"])})
323 except:
324 rowcols.append({"v": col["v"]})
325 rows.append({"c": rowcols})
326 table["rows"] = rows
327
328 if tqx:
329 reqId = tqx.strip("reqId:")
330 else:
331 reqId = "0"
332
333 result = {"status": "okColumnChart", "reqId": reqId, "table": table, "version": "0.6"}
334
335 result = "google.visualization.Query.setResponse(" + json.dumps(result) + ");"
336
337 def unquote_it(x): return x.group()[1:-1].replace('\\"', '"')
338
339 p = re.compile(r'"new Date\(\\"[^"]*\\"\)"')
340 result=p.sub(unquote_it, result)
341
342 return ("application/javascript", result)
343
Scott Baker43adf1b2014-03-19 21:54:55 -0700344 else:
Scott Baker95b28d62014-04-18 10:45:26 -0700345 if cached:
346 results = self.get_cached_query_results(self.compose_latest_query())
Scott Baker43adf1b2014-03-19 21:54:55 -0700347
Scott Baker95b28d62014-04-18 10:45:26 -0700348 filter={}
349 if slice:
350 filter["slice"] = slice
351 if site:
352 filter["site"] = site
353 if node:
354 filter["hostname"] = node
Scott Bakerc527fda2014-03-20 17:14:52 -0700355
Scott Baker95b28d62014-04-18 10:45:26 -0700356 result = self.postprocess_results(results, filter=filter, sum=sum, count=count, avg=avg, computed=computed, maxDeltaTime=120, groupBy=["doesnotexist"])
357 else:
358 result = self.run_query(q)
Scott Bakerc527fda2014-03-20 17:14:52 -0700359
Scott Baker43adf1b2014-03-19 21:54:55 -0700360 if maxRows:
361 result = result[-int(maxRows):]
362
Scott Baker95b28d62014-04-18 10:45:26 -0700363 if mergeDataModelSites:
364 self.merge_datamodel_sites(result)
Scott Baker43adf1b2014-03-19 21:54:55 -0700365
Scott Baker95b28d62014-04-18 10:45:26 -0700366 return self.format_result(format, result, q, dataSourceUrl)
Scott Baker43adf1b2014-03-19 21:54:55 -0700367
368def DoPlanetStackAnalytics(request):
369 bq = PlanetStackAnalytics()
370 result = bq.process_request(request)
371
372 return result
373
374def main():
375 bq = PlanetStackAnalytics()
376
Scott Baker95b28d62014-04-18 10:45:26 -0700377 q = bq.compose_latest_query()
378 results = bq.run_query(q)
379
380 results = bq.postprocess_results(results,
381 #filter={"site": "Princeton"},
382 groupBy=["site"],
383 computed=["bytes_sent/elapsed"],
384 sum=["bytes_sent", "computed_bytes_sent_div_elapsed"], avg=["cpu"],
385 maxDeltaTime=60)
386
387 bq.dump_table(results)
388
389 q=bq.compose_query(sum=["%bytes_sent"], avg=["%cpu"], latest=True, groupBy=["Time", "%site"])
390 print q
391 bq.dump_table(bq.run_query(q))
392
393 sys.exit(0)
394
Scott Baker050b1b82014-03-27 09:13:41 -0700395 q=bq.compose_query(avg=["%cpu","%bandwidth"], count=["%hostname"], slice="HyperCache")
Scott Baker43adf1b2014-03-19 21:54:55 -0700396 print q
397 bq.dump_table(bq.run_query(q))
398
399 q=bq.compose_query(computed=["%bytes_sent/%elapsed"])
400 print
401 print q
402 bq.dump_table(bq.run_query(q))
Scott Baker43adf1b2014-03-19 21:54:55 -0700403
Scott Baker050b1b82014-03-27 09:13:41 -0700404 q=bq.compose_query(timeBucket=60*60, avg=["%cpu"], count=["%hostname"], computed=["%bytes_sent/%elapsed"])
Scott Baker43adf1b2014-03-19 21:54:55 -0700405 print
406 print q
407 bq.dump_table(bq.run_query(q))
Scott Bakerc527fda2014-03-20 17:14:52 -0700408
Scott Baker43adf1b2014-03-19 21:54:55 -0700409if __name__ == "__main__":
410 main()
411
412
413
414
415