def _vars(request): profile = getProfile(request) out = '<font color="#77ddcc">' for variable in profile.variable_set.all(): out += '%s = %s<br/>' % (variable.name,variable.value) out += '</font>' return stdout(out)
def _dosave(request,viewName): profile = getProfile(request) #First find our View log.info("Saving view '%s' under profile '%s'" % (viewName,profile.user.username)) try: view = profile.view_set.get(name=viewName) except ObjectDoesNotExist: view = View(profile=profile,name=viewName) view.save() #Now re-associate the view with the correct Windows view.window_set.all().delete() for windowName,encodedString in request.GET.items(): try: if windowName in ('_','commandInput'): continue paramString = urllib.unquote_plus(encodedString) queryParams = cgi.parse_qs(paramString) modelParams = {} for key,value in queryParams.items(): #Clean up the window params key = str(key) value = str(value[0]) if key in ('top','left'): value = int(float( value.replace('px','') )) if key in ('width','height','interval'): value = int(float(value)) modelParams[key] = value if 'interval' not in modelParams: modelParams['interval'] = None win = Window(view=view,name=windowName,**modelParams) win.save() except: log.exception("Failed to process parameters for window '%s'" % windowName) return stdout('Saved view %s' % viewName)
def _views(request): out = '' profile = getProfile(request) for view in profile.view_set.all(): windowList = ','.join([window.name for window in view.window_set.all()]) out += stdout("%s: %s" % (view.name,windowList)) return out
def updateProfile(request): profile = getProfile(request,allowDefault=False) if profile: profile.advancedUI = request.POST.get('advancedUI','off') == 'on' profile.save() nextPage = request.POST.get('nextPage','/graphite') return HttpResponseRedirect(nextPage)
def _rmview(request,viewName): profile = getProfile(request) try: view = profile.view_set.get(name=viewName) except ObjectDoesNotExist: return stderr("No such view '%s'" % viewName) view.delete() return stdout("Deleted view %s" % viewName)
def _rmgraph(request,graphName): profile = getProfile(request,allowDefault=False) try: graph = profile.mygraph_set.get(name=graphName) except ObjectDoesNotExist: return stderr("No such graph %s" % graphName) graph.delete() return stdout("Deleted graph %s" % graphName)
def _unset(request,name): profile = getProfile(request) try: variable = profile.variable_set.get(name=name) variable.delete() except ObjectDoesNotExist: return stderr("Unknown variable %s" % name) return ''
def header(request): "View for the header frame of the browser UI" context = {} context['user'] = request.user context['profile'] = getProfile(request) context['documentation_url'] = settings.DOCUMENTATION_URL context['login_url'] = settings.LOGIN_URL return render_to_response("graphite/browserHeader.html", context)
def _set(request,name,value): profile = getProfile(request) try: variable = profile.variable_set.get(name=name) variable.value = value except ObjectDoesNotExist: variable = Variable(profile=profile,name=name,value=value) variable.save() return ''
def _gsave(request,graphName): profile = getProfile(request,allowDefault=False) if not profile: return stderr("You must be logged in to save graphs") out = "img = $('%s_img');\n" % graphName out += "if (!img) {\n" out += " alert('No such window');\n" out += "} else {\n" out += " queryString = 'commandInput=dogsave%%20%s&url=' + escape(img.src);\n" % graphName out += " savereq = new Ajax.Request('/graphite/cli/eval', {method: 'get', parameters: queryString, onException: handleException, onComplete: handleResponse});\n" out += "}\n" return out
def evaluate(request): if 'commandInput' not in request.GET: output = commands.stderr("No commandInput parameter!") return HttpResponse(output, mimetype='text/plain') #Variable substitution profile = getProfile(request) my_vars = {} for variable in profile.variable_set.all(): my_vars[variable.name] = variable.value cmd = request.GET['commandInput'] while '$' in cmd and not cmd.startswith('code'): i = cmd.find('$') j = i+1 for char in cmd[i+1:]: if char not in letters: break j += 1 var = cmd[i+1:j] if var in my_vars: cmd = cmd[:i] + my_vars[var] + cmd[j:] else: output = commands.stderr("Unknown variable %s" % var) return HttpResponse(output, mimetype='text/plain') if cmd == '?': cmd = 'help' try: tokens = parser.parseInput(cmd) if not tokens.command: output = commands.stderr("Invalid syntax") return HttpResponse(output, mimetype='text/plain') handler_name = '_' + tokens.command handler = vars(commands).get(handler_name) if handler is None: output = commands.stderr("Unknown command") return HttpResponse(output, mimetype='text/plain') args = dict( tokens.items() ) del args['command'] output = handler(request, **args) except: output = commands.printException() #Save command to history history = profile.history.split('\n') history.insert(0,cmd) while len(history) > 30: history.pop() profile.history = '\n'.join(history) profile.save() return HttpResponse(output, mimetype='text/plain')
def autocomplete(request): assert 'path' in request.GET, "Invalid request, no 'path' parameter!" path = request.GET['path'] shortnames = bool( request.GET.get('short') ) if request.GET['path'][:1] == '!': profile = getProfile(request) html = completer.completeHistory(path, profile) else: html = completer.completePath(path, shortnames=shortnames) return HttpResponse( html )
def composer(request): profile = getProfile(request) context = { 'queryString' : request.GET.urlencode().replace('+','%20'), 'showTarget' : request.GET.get('showTarget',''), 'user' : request.user, 'profile' : profile, 'showMyGraphs' : int( profile.user.username != 'default' ), 'searchEnabled' : int( os.access(settings.INDEX_FILE, os.R_OK) ), 'debug' : settings.DEBUG, 'jsdebug' : settings.DEBUG, } return render_to_response("graphite/composer.html",context)
def _gload(request,user=None,graphName=None): if not user: profile = getProfile(request,allowDefault=False) if not profile: return stderr("You are not logged in so you must specify a username") else: try: profile = getProfileByUsername(user) except ObjectDoesNotExist: return stderr("User does not exist") try: myGraph = profile.mygraph_set.get(name=graphName) except ObjectDoesNotExist: return stderr("Graph does not exist") out = _create(request,myGraph.name) out += "changeImage(%s_win,'%s');\n" % (myGraph.name.replace('.', '_'), myGraph.url) return out
def _graphs(request,user=None): if not user: profile = getProfile(request,allowDefault=False) if not profile: return stderr("You are not logged in so you must specify a username") else: try: profile = getProfileByUsername(user) except ObjectDoesNotExist: return stderr("User does not exist") out = "" if user: prefix = "~%s/" % user else: prefix = "" for graph in profile.mygraph_set.all(): out += stdout(prefix + graph.name) return out
def _dogsave(request,graphName): profile = getProfile(request,allowDefault=False) if not profile: return stderr("You must be logged in to save graphs") url = request.GET.get('url') if not url: return stderr("No url specified!") try: existingGraph = profile.mygraph_set.get(name=graphName) existingGraph.url = url existingGraph.save() except ObjectDoesNotExist: try: newGraph = MyGraph(profile=profile,name=graphName,url=url) newGraph.save() except: log.exception("Failed to create new MyGraph in _dogsave(), graphName=%s" % graphName) return stderr("Failed to save graph %s" % graphName) return stdout("Saved graph %s" % graphName)
def mygraph(request): profile = getProfile(request, allowDefault=False) if not profile: return HttpResponse( "You are not logged in!" ) action = request.GET['action'] graphName = request.GET['graphName'] if not graphName: return HttpResponse("You must type in a graph name.") if action == 'save': url = request.GET['url'] try: existingGraph = profile.mygraph_set.get(name=graphName) existingGraph.url = url existingGraph.save() except ObjectDoesNotExist: try: newGraph = MyGraph(profile=profile,name=graphName,url=url) newGraph.save() except: log.exception("Failed to create new MyGraph in /graphite/composer/mygraph/, graphName=%s" % graphName) return HttpResponse("Failed to save graph %s" % graphName) return HttpResponse("SAVED") elif action == 'delete': try: existingGraph = profile.mygraph_set.get(name=graphName) existingGraph.delete() except ObjectDoesNotExist: return HttpResponse("No such graph '%s'" % graphName) return HttpResponse("DELETED") else: return HttpResponse("Invalid operation '%s'" % action)
def _load(request,viewName,above=None): if above: out = stdout("Loading view %s above the current view" % viewName) else: out = stdout("Loading view %s" % viewName) profile = getProfile(request) try: view = profile.view_set.get(name=viewName) except ObjectDoesNotExist: return stderr("Unknown view %s" % viewName) if not above: out += "Windows.windows.each( function(w) {w.destroy();} );" for window in view.window_set.all(): out += _create(request,window.name) out += "win = %s_win;" % window.name out += "$('%s_img').src = '%s';" % (window.name,window.url) out += "win.show();" out += "win.setLocation(%d,%d);" % (window.top,window.left) out += "win.setSize(%d,%d);" % (window.width,window.height) if window.interval: out += "window.%s_interval = %d;" % (window.name,window.interval) out += "window.%s_timer = setTimeout('window.%s_redraw()', window.%s_interval);" % ((window.name,) * 3) return out
def find_view(request): "View for finding metrics matching a given pattern" profile = getProfile(request) format = request.REQUEST.get('format', 'treejson') local_only = int( request.REQUEST.get('local', 0) ) contexts = int( request.REQUEST.get('contexts', 0) ) wildcards = int( request.REQUEST.get('wildcards', 0) ) automatic_variants = int( request.REQUEST.get('automatic_variants', 0) ) try: query = str( request.REQUEST['query'] ) except: return HttpResponseBadRequest(content="Missing required parameter 'query'", mimetype="text/plain") if '.' in query: base_path = query.rsplit('.', 1)[0] + '.' else: base_path = '' if local_only: store = LOCAL_STORE else: store = STORE if format == 'completer': query = query.replace('..', '*.') if not query.endswith('*'): query += '*' if automatic_variants: query_parts = query.split('.') for i,part in enumerate(query_parts): if ',' in part and '{' not in part: query_parts[i] = '{%s}' % part query = '.'.join(query_parts) try: matches = list( store.find(query) ) except: log.exception() raise log.info('find_view query=%s local_only=%s matches=%d' % (query, local_only, len(matches))) matches.sort(key=lambda node: node.name) if format == 'treejson': content = tree_json(matches, base_path, wildcards=profile.advancedUI or wildcards, contexts=contexts) response = HttpResponse(content, mimetype='application/json') elif format == 'pickle': content = pickle_nodes(matches, contexts=contexts) response = HttpResponse(content, mimetype='application/pickle') elif format == 'completer': #if len(matches) == 1 and (not matches[0].isLeaf()) and query == matches[0].metric_path + '*': # auto-complete children # matches = list( store.find(query + '.*') ) results = [] for node in matches: node_info = dict(path=node.metric_path, name=node.name, is_leaf=str(int(node.isLeaf()))) if not node.isLeaf(): node_info['path'] += '.' results.append(node_info) if len(results) > 1 and wildcards: wildcardNode = {'name' : '*'} results.append(wildcardNode) content = json.dumps({ 'metrics' : results }) response = HttpResponse(content, mimetype='application/json') else: return HttpResponseBadRequest(content="Invalid value for 'format' parameter", mimetype="text/plain") response['Pragma'] = 'no-cache' response['Cache-Control'] = 'no-cache' return response
def editProfile(request): if not request.user.is_authenticated(): return HttpResponseRedirect('../..') context = { 'profile' : getProfile(request) } return render_to_response("graphite/editProfile.html",context)
def myGraphLookup(request): "View for My Graphs navigation" profile = getProfile(request,allowDefault=False) assert profile nodes = [] leafNode = { 'allowChildren' : 0, 'expandable' : 0, 'leaf' : 1, } branchNode = { 'allowChildren' : 1, 'expandable' : 1, 'leaf' : 0, } try: path = str( request.GET['path'] ) if path: if path.endswith('.'): userpath_prefix = path else: userpath_prefix = path + '.' else: userpath_prefix = "" matches = [ graph for graph in profile.mygraph_set.all().order_by('name') if graph.name.startswith(userpath_prefix) ] log.info( "myGraphLookup: username=%s, path=%s, userpath_prefix=%s, %ld graph to process" % (profile.user.username, path, userpath_prefix, len(matches)) ) branch_inserted = set() leaf_inserted = set() for graph in matches: #Now let's add the matching graph isBranch = False dotPos = graph.name.find( '.', len(userpath_prefix) ) if dotPos >= 0: isBranch = True name = graph.name[ len(userpath_prefix) : dotPos ] if name in branch_inserted: continue branch_inserted.add(name) else: name = graph.name[ len(userpath_prefix): ] if name in leaf_inserted: continue leaf_inserted.add(name) node = {'text' : str(name) } if isBranch: node.update( { 'id' : str(userpath_prefix + name + '.') } ) node.update(branchNode) else: m = md5() m.update(name) node.update( { 'id' : str(userpath_prefix + m.hexdigest()), 'graphUrl' : str(graph.url) } ) node.update(leafNode) nodes.append(node) except: log.exception("browser.views.myGraphLookup(): could not complete request.") if not nodes: no_graphs = { 'text' : "No saved graphs", 'id' : 'no-click' } no_graphs.update(leafNode) nodes.append(no_graphs) return json_response(nodes, request)
def cli(request): context = dict( request.GET.items() ) context['user'] = request.user context['profile'] = getProfile(request) return render_to_response("graphite/cli.html", context)