Browse Source

switch to access api module api

laiwei 8 years ago
parent
commit
46a6adc997

+ 3 - 17
rrd/config.py

@@ -1,20 +1,6 @@
 #-*-coding:utf8-*-
 import os
 
-#-- dashboard db config --
-DASHBOARD_DB_HOST = "127.0.0.1"
-DASHBOARD_DB_PORT = 3306
-DASHBOARD_DB_USER = "root"
-DASHBOARD_DB_PASSWD = ""
-DASHBOARD_DB_NAME = "dashboard"
-
-#-- graph db config --
-GRAPH_DB_HOST = "127.0.0.1"
-GRAPH_DB_PORT = 3306
-GRAPH_DB_USER = "root"
-GRAPH_DB_PASSWD = ""
-GRAPH_DB_NAME = "graph"
-
 #-- app config --
 DEBUG = True
 SECRET_KEY = "secret-key"
@@ -22,12 +8,12 @@ SESSION_COOKIE_NAME = "open-falcon"
 PERMANENT_SESSION_LIFETIME = 3600 * 24 * 30
 SITE_COOKIE = "open-falcon-ck"
 
-#-- query config --
-QUERY_ADDR = "http://127.0.0.1:9966"
-
 BASE_DIR = "/home/work/open-falcon/dashboard/"
 LOG_PATH = os.path.join(BASE_DIR,"log/")
 
+#-- API -- 
+API_ADDR = "http://127.0.0.1:8080/api/v1"
+
 try:
     from rrd.local_config import *
 except:

+ 24 - 0
rrd/corelib/__init__.py

@@ -0,0 +1,24 @@
+#-*- coding:utf-8 -*-
+from rrd import config 
+from rrd.utils import randbytes
+
+def auth_user_from_session(session_):
+    user = None
+    if config.SITE_COOKIE in session_:
+        cookies = session_[config.SITE_COOKIE]
+        user_id, session_id = cookies.split(":")
+
+    return user 
+
+def set_user_cookie(user, session_):
+    if not user:
+        return None
+    session_id = user.session_id if user.session_id else randbytes(8)
+    #user.update_session(session_id)
+    session_[config.SITE_COOKIE] = "%s:%s" % (user.id, session_id)
+
+def logout_user(user):
+    if not user:
+        return 
+    #user.clear_session()
+

+ 0 - 82
rrd/model/endpoint.py

@@ -1,82 +0,0 @@
-#-*- coding:utf-8 -*-
-from rrd.store import graph_db_conn as db_conn
-
-class Endpoint(object):
-    def __init__(self, id, endpoint, ts):
-        self.id = str(id)
-        self.endpoint = endpoint
-        self.ts = ts
-
-    def __repr__(self):
-        return "<Endpoint id=%s, endpoint=%s>" %(self.id, self.id)
-    __str__ = __repr__
-
-    @classmethod
-    def search(cls, qs, start=0, limit=100, deadline=0):
-        args = [deadline, ]
-        for q in qs:
-            args.append("%"+q+"%")
-        args += [start, limit]
-
-        sql = '''select id, endpoint, ts from endpoint where ts > %s '''
-        for q in qs:
-            sql += ''' and endpoint like %s'''
-        sql += ''' limit %s,%s'''
-
-        cursor = db_conn.execute(sql, args)
-        rows = cursor.fetchall()
-        cursor and cursor.close()
-
-        return [cls(*row) for row in rows]
-
-    @classmethod
-    def search_in_ids(cls, qs, ids, deadline=0):
-        if not ids:
-            return []
-
-        holders = ["%s" for x in ids]
-        placeholder = ",".join(holders)
-
-        args = ids + [deadline, ]
-        for q in qs:
-            args.append("%"+q+"%")
-
-        sql = '''select id, endpoint, ts from endpoint where id in (''' + placeholder + ''') and ts > %s '''
-        for q in qs:
-            sql += ''' and endpoint like %s'''
-
-        cursor = db_conn.execute(sql, args)
-        rows = cursor.fetchall()
-        cursor and cursor.close()
-
-        return [cls(*row) for row in rows]
-
-    @classmethod
-    def gets_by_endpoint(cls, endpoints, deadline=0):
-        if not endpoints:
-            return []
-
-        holders = ["%s" for x in endpoints]
-        placeholder = ",".join(holders)
-        args = endpoints + [deadline, ]
-
-        cursor = db_conn.execute('''select id, endpoint, ts from endpoint where endpoint in (''' + placeholder + ''') and ts > %s''', args)
-        rows = cursor.fetchall()
-        cursor and cursor.close()
-
-        return [cls(*row) for row in rows]
-
-    @classmethod
-    def gets(cls, ids, deadline=0):
-        if not ids:
-            return []
-
-        holders = ["%s" for x in ids]
-        placeholder = ",".join(holders)
-        args = ids + [deadline, ]
-
-        cursor = db_conn.execute('''select id, endpoint, ts from endpoint where id in (''' + placeholder + ''') and ts > %s''', args)
-        rows = cursor.fetchall()
-        cursor and cursor.close()
-
-        return [cls(*row) for row in rows]

+ 0 - 68
rrd/model/endpoint_counter.py

@@ -1,68 +0,0 @@
-#-*- coding:utf-8 -*-
-from rrd.store import graph_db_conn as db_conn
-
-class EndpointCounter(object):
-    def __init__(self, id, endpoint_id, counter, step, type_):
-        self.id = str(id)
-        self.endpoint_id = str(endpoint_id)
-        self.counter = counter
-        self.step = step
-        self.type_ = type_
-
-    def __repr__(self):
-        return "<EndpointCounter id=%s, endpoint_id=%s, counter=%s>" %(self.id, self.endpoint_id, self.counter)
-    __str__ = __repr__
-
-    @classmethod
-    def search_in_endpoint_ids(cls, qs, endpoint_ids, start=0, limit=100):
-        if not endpoint_ids:
-            return []
-
-        holders = ["%s" for x in endpoint_ids]
-        placeholder = ",".join(holders)
-
-        args = endpoint_ids
-        for q in qs:
-            args.append("%"+q+"%")
-        args += [start, limit]
-
-        sql = '''select id, endpoint_id, counter, step, type from endpoint_counter where endpoint_id in (''' +placeholder+ ''') '''
-        for q in qs:
-            sql += ''' and counter like %s'''
-        sql += ''' limit %s,%s'''
-
-        cursor = db_conn.execute(sql, args)
-        rows = cursor.fetchall()
-        cursor and cursor.close()
-
-        return [cls(*row) for row in rows]
-
-    @classmethod
-    def gets_by_endpoint_ids(cls, endpoint_ids, start=0, limit=100):
-        if not endpoint_ids:
-            return []
-
-        holders = ["%s" for x in endpoint_ids]
-        placeholder = ",".join(holders)
-        args = endpoint_ids + [start, limit]
-
-        cursor = db_conn.execute('''select id, endpoint_id, counter, step, type from endpoint_counter where endpoint_id in ('''+placeholder+''') limit %s, %s''', args)
-        rows = cursor.fetchall()
-        cursor and cursor.close()
-
-        return [cls(*row) for row in rows]
-
-    @classmethod
-    def gets(cls, ids, deadline=0):
-        if not ids:
-            return []
-
-        holders = ["%s" for x in ids]
-        placeholder = ",".join(holders)
-        args = ids + [start, limit]
-
-        cursor = db_conn.execute('''select id, endpoint, ts from endpoint where id in ('''+placeholder+''') and ts > %s''', args)
-        rows = cursor.fetchall()
-        cursor and cursor.close()
-
-        return [cls(*row) for row in rows]

+ 61 - 102
rrd/model/graph.py

@@ -1,9 +1,7 @@
 #-*- coding:utf-8 -*-
-import hashlib
-import datetime
-from rrd.store import dashboard_db_conn as db_conn
-from rrd.store import graph_db_conn
-from rrd.consts import ENDPOINT_DELIMITER, COUNTER_DELIMITER
+import json
+import requests
+from rrd.config import API_ADDR
 
 class DashboardGraph(object):
     def __init__(self, id, title, hosts, counters, screen_id,
@@ -25,81 +23,93 @@ class DashboardGraph(object):
 
     @classmethod
     def gets_by_screen_id(cls, screen_id):
-        cursor = db_conn.execute('''select id, title, hosts, counters, screen_id,
-                timespan, graph_type, method, position 
-                from dashboard_graph where screen_id=%s order by position''', (screen_id,))
-        rows = cursor.fetchall()
-        cursor and cursor.close()
-        ret = []
-        for row in rows:
-            args = list(row)
-            args[2] = args[2].split(ENDPOINT_DELIMITER) or []
-            args[3] = args[3].split(ENDPOINT_DELIMITER) or []
-            ret.append(cls(*args))
-        return ret
+        r = requests.get(API_ADDR + "/dashboard/graphs/screen/%s" %(screen_id,))
+        if r.status_code != 200:
+            return
+        j = r.json()
+        return [cls(*[x["graph_id"], x["title"], x["endpoints"], x["counters"], \
+                x["screen_id"], x["timespan"], x["graph_type"], x["method"], x["position"]]) for x in j]
 
     @classmethod
     def get(cls, id):
-        cursor = db_conn.execute('''select id, title, hosts, counters, screen_id,
-                timespan, graph_type, method, position
-                from dashboard_graph where id=%s''', (id,))
-        row = cursor.fetchone()
-        cursor and cursor.close()
-        if row:
-            args = list(row)
-            args[2] = args[2].split(ENDPOINT_DELIMITER) or []
-            args[3] = args[3].split(ENDPOINT_DELIMITER) or []
-            return cls(*args)
+        r = requests.get(API_ADDR + "/dashboard/graph/%s" %(id,))
+        if r.status_code != 200:
+            return
+        x = r.json()
+        return x and cls(*[x["graph_id"], x["title"], x["endpoints"], x["counters"], \
+                x["screen_id"], x["timespan"], x["graph_type"], x["method"], x["position"]])
 
     @classmethod
     def add(cls, title, hosts, counters, screen_id,
                 timespan=3600, graph_type='h', method='', position=0):
-        cursor = db_conn.execute('''insert into dashboard_graph (title, hosts, counters, screen_id,
-                timespan, graph_type, method, position)
-                values(%s, %s, %s, %s, %s, %s, %s, %s)''',
-                (title, ENDPOINT_DELIMITER.join(hosts) or "", ENDPOINT_DELIMITER.join(counters) or "", screen_id,
-                    timespan, graph_type, method, position))
-        id_ = cursor.lastrowid
-        db_conn.execute('''update dashboard_graph set position=%s where id=%s''', (id_, id_))
-        db_conn.commit()
-        cursor and cursor.close()
-        return cls.get(id_)
+
+        d = {
+            "screen_id": screen_id,
+            "title": title,
+            "endpoints": hosts,
+            "counters": counters,
+            "timespan": timespan,
+            "graph_type": graph_type,
+            "method": method,
+            "position": position,
+            "falcon_tags": "",
+        }
+        h = {"Content-type": "application/json"}
+        r = requests.post(API_ADDR + "/dashboard/graph", data = json.dumps(d), headers =h )
+        if r.status_code != 200:
+            return
+        j = r.json()
+
+        graph_id = j and j.get("id")
+        return graph_id and cls.get(graph_id)
 
     @classmethod
     def remove(cls, id):
-        db_conn.execute('''delete from dashboard_graph where id=%s''', (id,))
-        db_conn.commit()
+        r = requests.delete(API_ADDR + "/dashboard/graph/%s" %(id,))
+        if r.status_code != 200:
+            return
+        return r.json()
 
     def update(self, title=None, hosts=None, counters=None, screen_id=None,
             timespan=None, graph_type=None, method=None, position=None):
 
         title = self.title if title is None else title
         hosts = self.hosts if hosts is None else hosts
-        hosts = hosts and ENDPOINT_DELIMITER.join(hosts) or ""
-
         counters = self.counters if counters is None else counters
-        counters = counters and ENDPOINT_DELIMITER.join(counters) or ""
-
         screen_id = screen_id or self.screen_id
         timespan = timespan or self.timespan
         graph_type = graph_type or self.graph_type
         method = method if method is not None else self.method
         position = position or self.position
-        db_conn.execute('''update dashboard_graph set title=%s, hosts=%s, counters=%s, screen_id=%s,
-                    timespan=%s, graph_type=%s, method=%s, position=%s where id=%s''',
-                    (title, hosts, counters, screen_id, timespan, graph_type, method, position, self.id))
-        db_conn.commit()
-        return DashboardGraph.get(self.id)
     
+        d = {
+            "screen_id": screen_id,
+            "title": title,
+            "endpoints": hosts,
+            "counters": counters,
+            "timespan": timespan,
+            "graph_type": graph_type,
+            "method": method,
+            "position": position,
+            "falcon_tags": "",
+        }
+        h = {"Content-type": "application/json"}
+        r = requests.put(API_ADDR + "/dashboard/graph/%s" %(self.id,), data = json.dumps(d), headers =h )
+        if r.status_code != 200:
+            return
+        j = r.json()
+
+        graph_id = j and j.get("id")
+        return graph_id and cls.get(graph_id)
+
     @classmethod
     def update_multi(cls, rows):
         for x in rows:
             id = x["id"]
             hosts = x["hosts"] or []
             counters = x["counters"] or []
-            db_conn.execute('''update dashboard_graph set hosts=%s, counters=%s where id=%s''',
-                    (ENDPOINT_DELIMITER.join(hosts) or "", ENDPOINT_DELIMITER.join(counters) or "", id))
-        db_conn.commit()
+            grh = cls.get(id)
+            grh and grh.update(hosts=hosts, counters=counters)
         
 
 
@@ -118,54 +128,3 @@ CREATE TABLE `dashboard_graph` (
   KEY `idx_sid` (`screen_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
 '''
-
-class TmpGraph(object):
-    def __init__(self, id, endpoints, counters, time_):
-        self.id = str(id)
-        self.endpoints = endpoints or []
-        self.endpoints = filter(None, [x.strip() for x in self.endpoints])
-        self.counters = counters or []
-        self.counters = filter(None, [x.strip() for x in self.counters])
-        self.time_ = time_
-
-    def __repr__(self):
-        return "<TmpGraph id=%s, endpoints=%s, counters=%s>" %(self.id, self.endpoints, self.counters)
-    __str__ = __repr__
-
-    @classmethod
-    def get(cls, id):
-        cursor = db_conn.execute('''select id, endpoints, counters, time_ from tmp_graph where id=%s''', (id,))
-        row = cursor.fetchone()
-        cursor and cursor.close()
-        if row:
-            id, endpoints, counters, time_ = row
-            endpoint_list = endpoints and endpoints.split(ENDPOINT_DELIMITER) or []
-            counter_list = counters and counters.split(ENDPOINT_DELIMITER) or []
-            return cls(id, endpoint_list, counter_list, time_)
-        else:
-            return None
-
-
-    @classmethod
-    def add(cls, endpoints, counters):
-        es = endpoints and ENDPOINT_DELIMITER.join(sorted(endpoints)) or ""
-        cs = counters and COUNTER_DELIMITER.join(sorted(counters)) or ""
-        ck = hashlib.md5("%s:%s" %(es.encode("utf8"), cs.encode("utf8"))).hexdigest()
-        cursor = db_conn.execute('''insert ignore into tmp_graph (endpoints, counters, ck) values(%s, %s, %s) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id),time_=%s''',
-                (es, cs, ck, datetime.datetime.now()))
-        id_ = cursor.lastrowid
-        db_conn.commit()
-        cursor and cursor.close()
-        return id_
-
-'''
-CREATE TABLE `tmp_graph` (
-`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
-`endpoints` varchar(10240) NOT NULL DEFAULT '',
-`counters` varchar(10240) NOT NULL DEFAULT '',
-`ck` varchar(32) NOT NULL,
-`time_` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
-PRIMARY KEY (`id`),
-UNIQUE KEY `idx_ck` (`ck`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8
-'''

+ 45 - 34
rrd/model/screen.py

@@ -1,12 +1,13 @@
 #-*- coding:utf-8 -*-
-from rrd.store import dashboard_db_conn as db_conn
+import json
+import requests
+from rrd.config import API_ADDR
 
 class DashboardScreen(object):
-    def __init__(self, id, pid, name, time):
+    def __init__(self, id, pid, name):
         self.id = str(id)
         self.pid = str(pid)
         self.name = name
-        self.time = time
 
     def __repr__(self):
         return "<DashboardScreen id=%s, name=%s, pid=%s>" %(self.id, self.name, self.pid)
@@ -14,44 +15,54 @@ class DashboardScreen(object):
 
     @classmethod
     def get(cls, id):
-        cursor = db_conn.execute('''select id, pid, name, time from dashboard_screen where id=%s''', (id,))
-        row = cursor.fetchone()
-        cursor.close()
-        return row and cls(*row)
+        r = requests.get(API_ADDR + "/dashboard/screen/%s" %(id,))
+        if r.status_code != 200:
+            return
+        j = r.json()
+        if j:
+            row = [j["id"], j["pid"], j["name"]]
+            return cls(*row)
 
     @classmethod
-    def gets(cls, pid=None, start=0, limit=0):
-        assert limit >= 0
-        if pid is not None:
-            if limit > 0:
-                cursor = db_conn.execute('''select id, pid, name, time from dashboard_screen where pid=%s limit %s, %s''', (pid, start, limit))
-            else:
-                cursor = db_conn.execute('''select id, pid, name, time from dashboard_screen where pid=%s''', (pid,))
-        else:
-            if limit > 0:
-                cursor = db_conn.execute('''select id, pid, name, time from dashboard_screen limit %s, %s''', (start, limit))
-            else:
-                cursor = db_conn.execute('''select id, pid, name, time from dashboard_screen''')
-        rows = cursor.fetchall()
-        cursor.close()
-        return [cls(*row) for row in rows]
+    def gets_by_pid(cls, pid):
+        r = requests.get(API_ADDR + "/dashboard/screens/pid/%s" %(pid,))
+        if r.status_code != 200:
+            return
+        j = r.json()
+        return [cls(*[x["id"], x["pid"], x["name"]]) for x in j]
+
+    @classmethod
+    def gets_all(cls, limit=500):
+        r = requests.get(API_ADDR + "/dashboard/screens?limit=%s" %(limit,))
+        if r.status_code != 200:
+            return
+        j = r.json()
+        return [cls(*[x["id"], x["pid"], x["name"]]) for x in j]
 
     @classmethod
     def add(cls, pid, name):
-        cursor = db_conn.execute('''insert into dashboard_screen (pid, name) values(%s, %s)''', (pid, name))
-        id_ = cursor.lastrowid
-        db_conn.commit()
-        cursor.close()
-        return cls.get(id_)
+        d = {"pid": pid, "name": name}
+        r = requests.post(API_ADDR + "/dashboard/screen", data = d)
+        if r.status_code != 200:
+            return
+        j = r.json()
+        return cls(*[j["id"], j["pid"], j["name"]])
 
     @classmethod
     def remove(cls, id):
-        db_conn.execute('''delete from dashboard_screen where id=%s''', (id,))
-        db_conn.commit()
+        r = requests.delete(API_ADDR + "/dashboard/screen/%s" %(id,))
+        if r.status_code != 200:
+            return
+        return r.json()
 
     def update(self, pid=None, name=None):
-        pid = pid or self.pid
-        name = name or self.name
-        db_conn.execute('''update dashboard_screen set pid=%s, name=%s where id=%s''', (pid, name, self.id))
-        db_conn.commit()
-        return DashboardScreen.get(self.id)
+        d = {}
+        if pid:
+            d["pid"] = pid
+        if name:
+            d["name"] = name
+
+        r = requests.put(API_ADDR + "/dashboard/screen/%s" %self.id, data = d)
+        if r.status_code != 200:
+            return
+        return r.json()

+ 0 - 47
rrd/model/tag_endpoint.py

@@ -1,47 +0,0 @@
-#-*- coding:utf-8 -*-
-from rrd.store import graph_db_conn as db_conn
-
-class TagEndpoint(object):
-    def __init__(self, id, tag, endpoint_id):
-        self.id = str(id)
-        self.tag = tag
-        self.endpoint_id = str(endpoint_id)
-
-
-    @classmethod
-    def get_endpoint_ids(cls, tags, limit=200):
-        if not tags:
-            return []
-
-        holders = ["%s" for x in tags]
-        placeholder = ",".join(holders)
-        args = tags
-        cursor = db_conn.execute('''select distinct endpoint_id from tag_endpoint where tag in (''' + placeholder + ''')''', args)
-        rows = cursor.fetchall()
-        ids = [x[0] for x in rows]
-
-        if not ids:
-            return []
-
-        res = None
-        for t in tags:
-            holders = ["%s" for x in ids]
-            placeholder = ",".join(holders)
-            args = list(ids) + [t, ]
-            sql = '''select endpoint_id from tag_endpoint where endpoint_id in (''' + placeholder + ''') and tag=%s'''
-            cursor = db_conn.execute(sql, args)
-            rows = cursor.fetchall()
-            cursor and cursor.close()
-
-            if not rows:
-                return []
-
-            if res is None:
-                res = set([row[0] for row in rows])
-            else:
-                res.intersection_update(set([row[0] for row in rows]))
-
-        ret = list(res) if res else []
-        return ret[:limit]
-
-

+ 52 - 0
rrd/model/tmpgraph.py

@@ -0,0 +1,52 @@
+#-*- coding:utf-8 -*-
+import json
+import requests
+from rrd.config import API_ADDR
+
+class TmpGraph(object):
+    def __init__(self, id, endpoints, counters):
+        self.id = str(id)
+        self.endpoints = endpoints or []
+        self.endpoints = filter(None, [x.strip() for x in self.endpoints])
+        self.counters = counters or []
+        self.counters = filter(None, [x.strip() for x in self.counters])
+
+    def __repr__(self):
+        return "<TmpGraph id=%s, endpoints=%s, counters=%s>" %(self.id, self.endpoints, self.counters)
+    __str__ = __repr__
+
+    @classmethod
+    def get(cls, id):
+        r = requests.get(API_ADDR + "/dashboard/tmpgraph/%s" %(id,))
+        if r.status_code != 200:
+            return
+
+        j = r.json()
+        return j and cls(*[id, j["endpoints"], j["counters"]])
+
+
+    @classmethod
+    def add(cls, endpoints, counters):
+        d = {
+            "endpoints": endpoints,
+            "counters": counters,
+        }
+        headers = {'Content-type': 'application/json'}
+        r = requests.post(API_ADDR + "/dashboard/tmpgraph", headers=headers, data=json.dumps(d))
+        if r.status_code != 200:
+            return
+
+        j = r.json()
+        return j and j.get('id')
+
+'''
+CREATE TABLE `tmp_graph` (
+`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+`endpoints` varchar(10240) NOT NULL DEFAULT '',
+`counters` varchar(10240) NOT NULL DEFAULT '',
+`ck` varchar(32) NOT NULL,
+`time_` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+PRIMARY KEY (`id`),
+UNIQUE KEY `idx_ck` (`ck`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8
+'''

+ 14 - 0
rrd/model/user.py

@@ -0,0 +1,14 @@
+#-*- coding:utf-8 -*-
+class User(object):
+    def __init__(self, id):
+        self.name = None
+        self.session_id = None
+    
+    def __repr__(self):
+        return "<User name=%s, session_id=%s>" \
+                % (self.name, self.session_id)
+    __str__ = __repr__
+
+    @classmethod
+    def get(cls, name):
+        return None

+ 9 - 9
rrd/static/js/xperf.js

@@ -11,15 +11,15 @@ function fn_list_endpoints()
                     alert(ret.msg);
                     return;
                 }
-                var hosts = ret.data;
 
                 // display_endpoints
                 var tbody_hosts = $("#tbody-endpoints");
                 tbody_hosts.html("");
-                for (var hidx in hosts) {
-                    var h = hosts[hidx];
+                for (var hidx in ret.data) {
+                    var h = ret.data[hidx].endpoint;
+                    var eid = ret.data[hidx].id;
                     var line_html = '<tr>'
-                    + '<td><input type="checkbox" class="input shiftCheckbox" data-fullname="'+ h +'"></input></td>'
+                    + '<td><input type="checkbox" class="input shiftCheckbox" data-eid="'+ eid +'"  data-fullname="'+ h +'"></input></td>'
                     + '<td>' + h + '</td>'
                     + '</tr>';
                     tbody_hosts.append($(line_html));
@@ -34,12 +34,12 @@ function fn_list_endpoints()
 
 function fn_list_counters(){
     var qs = $.trim($("#counter-search").val());
-    var hosts = new Array();
+    var eids = new Array();
     $("#tbody-endpoints input:checked").each(function(i, o){
-        var name = $(o).attr("data-fullname");
-        hosts.push(name);
+        var eid = $(o).attr("data-eid");
+        eids.push(eid);
     });
-    if (hosts.length === 0){
+    if (eids.length === 0){
         alert("先选定一些endpoints");
         return false;
     }
@@ -50,7 +50,7 @@ function fn_list_counters(){
         method: "POST",
         url: "/api/counters",
         dataType: "json",
-        data: {"endpoints": JSON.stringify(hosts), "q": qs, "limit": limit, "_r": Math.random()},
+        data: {"eids": JSON.stringify(eids), "q": qs, "limit": limit, "_r": Math.random()},
         success:function(ret){
             $(".loading").hide();
             if(ret.ok){

+ 0 - 16
rrd/store.py

@@ -1,6 +1,5 @@
 #-*- coding:utf-8 -*-
 import MySQLdb
-from rrd import config
 
 def connect_db(host, port, user, password, db):
     try:
@@ -60,18 +59,3 @@ class DB(object):
                 self._conn and self._conn.close()
                 self.connect()
                 self._conn and self._conn.rollback()
-
-dashboard_db_conn = DB(
-        config.DASHBOARD_DB_HOST,
-        config.DASHBOARD_DB_PORT,
-        config.DASHBOARD_DB_USER,
-        config.DASHBOARD_DB_PASSWD,
-        config.DASHBOARD_DB_NAME)
-
-graph_db_conn = DB(
-        config.GRAPH_DB_HOST,
-        config.GRAPH_DB_PORT,
-        config.GRAPH_DB_USER,
-        config.GRAPH_DB_PASSWD,
-        config.GRAPH_DB_NAME)
-

+ 0 - 1
rrd/utils/__init__.py

@@ -7,4 +7,3 @@ def randbytes(bytes_):
 
 def random_string (length):
     return ''.join(random.choice(string.letters) for ii in range (length + 1))
-

+ 4 - 55
rrd/utils/graph_urls.py

@@ -4,10 +4,7 @@ import json
 import copy
 import re
 from rrd import config
-from rrd.consts import ENDPOINT_DELIMITER
-from rrd.model.graph import TmpGraph
-from rrd.model.endpoint import Endpoint
-from rrd.model.endpoint_counter import EndpointCounter
+from rrd.model.tmpgraph import TmpGraph
 
 def generate_graph_urls(graph, start, end):
     counters = graph.counters or []
@@ -18,50 +15,6 @@ def generate_graph_urls(graph, start, end):
     if not endpoint_list:
         return []
 
-    endpoint_objs = Endpoint.gets_by_endpoint(endpoint_list)
-    if not endpoint_objs:
-        return []
-    endpoint_ids = [x.id for x in endpoint_objs]
-
-    counters = []
-    for c in graph.counters:
-        if c.find("metric=") == -1:
-            counters.append(c)
-        else:
-            metric=""
-            tags = []
-            qs = []
-            c = c.strip()
-            for q in c.split():
-                q = q.strip()
-                if q.startswith("metric="):
-                    metric = q.replace("metric=", "", 1)
-                    qs.append(metric)
-                else:
-                    qs.append(q)
-                    tags.append(q)
-
-            counter_objs = EndpointCounter.search_in_endpoint_ids(qs, endpoint_ids[:], limit=100)
-            if not counter_objs:
-                continue
-            for co in counter_objs:
-                if not re.search('^%s(/|$)' %metric, co.counter):
-                    continue
-
-                matched = True
-                for tag in tags:
-                    if not re.search('(/|,)%s(,|$)' %tag, co.counter):
-                        matched = False
-                        break
-                if not matched:
-                    continue
-
-                counters.append(co.counter)
-
-    if not counters:
-        return []
-    counters = sorted(list(set(counters)))
-
     return _generate_graph_urls(graph, counters, endpoint_list, start, end)
 
 def _generate_graph_urls(graph, counters, endpoint_list, start, end):
@@ -69,7 +22,7 @@ def _generate_graph_urls(graph, counters, endpoint_list, start, end):
 
     if graph.graph_type == 'h':
         for c in counters:
-            tmp_graph_id = create_tmp_graph(endpoint_list, [c,])
+            tmp_graph_id = TmpGraph.add(endpoint_list, [c,])
             if not tmp_graph_id:
                 break
 
@@ -87,7 +40,7 @@ def _generate_graph_urls(graph, counters, endpoint_list, start, end):
             ret_graphs.append(new_g)
     elif graph.graph_type=='k':
         for e in endpoint_list:
-            tmp_graph_id = create_tmp_graph([e,], counters)
+            tmp_graph_id = TmpGraph.add([e,], counters)
             if not tmp_graph_id:
                 break
 
@@ -105,7 +58,7 @@ def _generate_graph_urls(graph, counters, endpoint_list, start, end):
             ret_graphs.append(new_g)
     else:
         #组合视角
-        tmp_graph_id = create_tmp_graph(endpoint_list, counters)
+        tmp_graph_id = TmpGraph.add(endpoint_list, counters)
         if not tmp_graph_id:
             return []
         new_g = copy.deepcopy(graph)
@@ -122,7 +75,3 @@ def _generate_graph_urls(graph, counters, endpoint_list, start, end):
 
     return ret_graphs
 
-def create_tmp_graph(endpoints, counters):
-    id_ = TmpGraph.add(endpoints, counters)
-    return id_
-

+ 11 - 107
rrd/utils/rrdgraph.py

@@ -1,119 +1,24 @@
 #-*- coding:utf-8 -*-
-import hashlib
-import json
-import dateutil.parser
-import time
-
 import requests
-from rrd.config import QUERY_ADDR
-
-def graph_info(endpoint_counter):
-    '''
-    params:
-        [
-                {
-                    "endpoint": "xx",
-                    "counter": "load.1min",
-                },
-                {
-                    "endpoint": "yy",
-                    "counter": "cpu.idle",
-                },
-        ]
-
-    return:
-        [
-            {
-                "Filename": "/home/work/data/6070/79/794a6adefed6b10550b4aaaf4c10d20c_GAUGE_60.rrd",
-                "addr": "graph1:6070",
-                "consolFuc": "GAUGE",
-                "counter": "load.1min",
-                "endpoint": "xx",
-                "step": 60
-            },
-            {
-                "Filename": "/home/work/data/6070/3c/3cb8b78377824b867c6324463ac736b6_GAUGE_60.rrd",
-                "addr": "graph2:6070",
-                "consolFuc": "GAUGE",
-                "counter": "cpu.idle",
-                "endpoint": "yy",
-                "step": 60
-            }
-        ]
-    '''
-
-    if not endpoint_counter:
-        return
-
-    r = requests.post("%s/graph/info" %QUERY_ADDR, data=json.dumps(endpoint_counter))
-    if r.status_code != 200:
-        raise
-
-    return r.json()
-
-def graph_query(endpoint_counters, cf, start, end):
-    '''
-    params:
-        endpoint_counters: [
-            {
-                "endpoint": "xx",
-                "counter": "load.1min",
-            },
-            {
-                "endpoint": "yy",
-                "counter": "cpu.idle",
-            },
-        ]
-
-    return:
-        [
-            {
-                "endpoint": "xx",
-                "counter": "yy",
-                "Values": [
-                    {
-                        "timestamp": 1422868140,
-                        "value": 0.32183299999999998
-                    },
-                    {
-                        "timestamp": 1422868200,
-                        "value": 0.406167
-                    },
-                ]
-            },
-            {
-                "endpoint": "xx",
-                "counter": "yy",
-                "Values": [
-                    {
-                        "timestamp": 1422868140,
-                        "value": 0.32183299999999998
-                    },
-                    {
-                        "timestamp": 1422868200,
-                        "value": 0.406167
-                    },
-                ]
-            },
-        ]
+from rrd.config import API_ADDR
+import json
 
-    '''
+def graph_history(endpoints, counters, cf, start, end):
+    #TODO:step
     params = {
-            "start": start,
-            "end": end,
-            "cf": cf,
-            "endpoint_counters": endpoint_counters,
+        "start_time": start,
+        "end_time": end,
+        "consol_fun": cf,
+        "hostnames": endpoints,
+        "counters": counters,
     }
-    r = requests.post("%s/graph/history" %QUERY_ADDR, data=json.dumps(params))
+    h = {"Content-type": "application/json"}
+    r = requests.post("%s/graph/history" %API_ADDR, headers=h, data=json.dumps(params))
     if r.status_code != 200:
         raise Exception("{} : {}".format(r.status_code, r.text))
 
     return r.json()
 
-def digest_key(endpoint, key):
-    s = "%s/%s" %(endpoint.encode("utf8"), key.encode("utf8"))
-    return hashlib.md5(s).hexdigest()[:16]
-
 def merge_list(a, b):
     sum = []
     a_len = len(a)
@@ -148,4 +53,3 @@ def CF(cf, values):
         return min(values)
     elif cf == 'LAST':
         return values[-1]
-

+ 50 - 0
rrd/view/__init__.py

@@ -0,0 +1,50 @@
+#-*- coding:utf-8 -*-
+import time
+from flask import request, g, abort, render_template
+from MySQLdb import ProgrammingError
+
+from rrd import app
+from rrd.consts import RRD_CFS, GRAPH_TYPE_KEY, GRAPH_TYPE_HOST
+
+@app.teardown_request
+def teardown_request(exception):
+    pass
+
+@app.before_request
+def chart_before():
+    if request.method == "GET":
+        now = int(time.time())
+
+        #是否显示顶部图表导航
+        g.nav_header = request.args.get("nav_header") or "on"
+        g.cols = request.args.get("cols") or "2"
+        try:
+            g.cols = int(g.cols)
+        except:
+            g.cols = 2
+        if g.cols <= 0:
+            g.cols = 2
+        if g.cols >= 6:
+            g.cols = 6
+
+        g.legend = request.args.get("legend") or "off"
+        g.graph_type = request.args.get("graph_type") or GRAPH_TYPE_HOST
+        g.sum = request.args.get("sum") or "off" #是否求和
+        g.sumonly = request.args.get("sumonly") or "off" #是否只显示求和
+
+        g.cf = (request.args.get("cf") or "AVERAGE").upper() # MAX, MIN, AVGRAGE, LAST
+
+        g.start = int(request.args.get("start") or -3600)
+        if g.start < 0:
+            g.start = now + g.start
+
+        g.end = int(request.args.get("end") or 0)
+        if g.end <= 0:
+            g.end = now + g.end
+        g.end = g.end - 60
+
+        g.id = request.args.get("id") or ""
+
+        g.limit = int(request.args.get("limit") or 0)
+        g.page = int(request.args.get("page") or 0)
+

+ 29 - 66
rrd/view/api.py

@@ -1,20 +1,17 @@
 #-*- coding:utf-8 -*-
 import json
+import requests
 from flask import request, abort, g
-from rrd import app
-
-from rrd.model.tag_endpoint import TagEndpoint
-from rrd.model.endpoint import Endpoint
-from rrd.model.endpoint_counter import EndpointCounter
-from rrd.model.graph import TmpGraph
+from rrd import app, config
 
+#done, TODO:query by tags
 @app.route("/api/endpoints")
 def api_endpoints():
     ret = {
-        "ok": False,
-        "msg": "",
-        "data": [],
-    }
+            "ok": False,
+            "msg": "",
+            "data": [],
+            }
 
     q = request.args.get("q") or ""
     raw_tag = request.args.get("tags") or ""
@@ -24,61 +21,45 @@ def api_endpoints():
     if not q and not tags:
         ret["msg"] = "no query params given"
         return json.dumps(ret)
-    
-    endpoints = []
 
-    if tags and q:
-        endpoint_ids = TagEndpoint.get_endpoint_ids(tags, limit=limit) or []
-        endpoints = Endpoint.search_in_ids(q.split(), endpoint_ids)
-    elif tags:
-        endpoint_ids = TagEndpoint.get_endpoint_ids(tags, limit=limit) or []
-        endpoints = Endpoint.gets(endpoint_ids)
-    else:
-        endpoints = Endpoint.search(q.split(), limit=limit)
+    r = requests.get(config.API_ADDR + "/graph/endpoint?q=%s&limit=%s&tags=%s" %(q, limit, tags))
+    if r.status_code != 200:
+        abort(400, r.text)
+
+    j = sorted(r.json(), key=lambda x:x["endpoint"])
+    endpoints = [x["endpoint"] for x in j]
 
-    endpoints_str = [x.endpoint for x in endpoints]
-    endpoints_str.sort()
-    ret['data'] = endpoints_str
+    ret['data'] = j
     ret['ok'] = True
 
     return json.dumps(ret)
 
-
+#done
 @app.route("/api/counters", methods=["POST"])
 def api_get_counters():
     ret = {
-        "ok": False,
-        "msg": "",
-        "data": [],
-    }
-    endpoints = request.form.get("endpoints") or ""
-    endpoints = endpoints and json.loads(endpoints)
+            "ok": False,
+            "msg": "",
+            "data": [],
+            }
+
     q = request.form.get("q") or ""
     limit = int(request.form.get("limit") or 100)
+    eids = request.form.get("eids") or ""
+    eids = eids and json.loads(eids) or []
 
-    if not (endpoints or q):
+    if not (eids or q):
         ret['msg'] = "no endpoints or counter given"
         return json.dumps(ret)
 
-    endpoint_objs = Endpoint.gets_by_endpoint(endpoints)
-    endpoint_ids = [x.id for x in endpoint_objs]
-    if not endpoint_ids:
-        ret['msg'] = "no endpoints in graph"
-        return json.dumps(ret)
-
-    if q:
-        qs = q.split()
-        ecs = EndpointCounter.search_in_endpoint_ids(qs, endpoint_ids, limit=limit)
-    else:
-        ecs = EndpointCounter.gets_by_endpoint_ids(endpoint_ids, limit=limit)
+    r = requests.get(config.API_ADDR + "/graph/endpoint_counter?eid=%s&metricQuery=%s&limit=%s" %(",".join(eids), q, limit))
+    if r.status_code != 200:
+        abort(400, r.text)
+    j = r.json()
 
-    if not ecs:
-        ret["msg"] = "no counters in graph"
-        return json.dumps(ret)
-    
     counters_map = {}
-    for x in ecs:
-        counters_map[x.counter] = [x.counter, x.type_, x.step]
+    for x in j:
+        counters_map[x['counter']] = [x['counter'], x['type'], x['step']]
     sorted_counters = sorted(counters_map.keys())
     sorted_values = [counters_map[x] for x in sorted_counters]
 
@@ -86,21 +67,3 @@ def api_get_counters():
     ret['ok'] = True
 
     return json.dumps(ret)
-
-@app.route("/api/tmpgraph", methods=["POST",])
-def api_create_tmpgraph():
-    d = request.data
-    jdata = json.loads(d)
-    endpoints = jdata.get("endpoints") or []
-    counters = jdata.get("counters") or []
-    id_ = TmpGraph.add(endpoints, counters)
-
-    ret = {
-        "ok": False,
-        "id": id_,
-    }
-    if id_:
-        ret['ok'] = True
-        return json.dumps(ret)
-    else:
-        return json.dumps(ret)

+ 42 - 125
rrd/view/chart.py

@@ -1,73 +1,13 @@
 #-*- coding:utf-8 -*-
-import os
-import time
-import datetime
-import socket
-import hashlib
-import random
 import urllib
 import json
-import random
 from flask import request, g, abort, render_template
-from MySQLdb import ProgrammingError
 
 from rrd import app
-from rrd.consts import RRD_CFS, GRAPH_TYPE_KEY, GRAPH_TYPE_HOST
-from rrd.model.graph import TmpGraph
+from rrd.consts import GRAPH_TYPE_KEY, GRAPH_TYPE_HOST
 from rrd.utils.rrdgraph import merge_list
-from rrd.utils.rrdgraph import graph_query
-
-@app.teardown_request
-def teardown_request(exception):
-    from rrd.store import dashboard_db_conn as db_conn
-    try:
-        db_conn and db_conn.commit()
-    except ProgrammingError:
-        pass
-
-    from rrd.store import graph_db_conn
-    try:
-        graph_db_conn and graph_db_conn.commit()
-    except ProgrammingError:
-        pass
-#
-@app.before_request
-def chart_before():
-    if request.method == "GET":
-        now = int(time.time())
-
-        #是否显示顶部图表导航
-        g.nav_header = request.args.get("nav_header") or "on"
-        g.cols = request.args.get("cols") or "2"
-        try:
-            g.cols = int(g.cols)
-        except:
-            g.cols = 2
-        if g.cols <= 0:
-            g.cols = 2
-        if g.cols >= 6:
-            g.cols = 6
-
-        g.legend = request.args.get("legend") or "off"
-        g.graph_type = request.args.get("graph_type") or GRAPH_TYPE_HOST
-        g.sum = request.args.get("sum") or "off" #是否求和
-        g.sumonly = request.args.get("sumonly") or "off" #是否只显示求和
-
-        g.cf = (request.args.get("cf") or "AVERAGE").upper() # MAX, MIN, AVGRAGE, LAST
-
-        g.start = int(request.args.get("start") or -3600)
-        if g.start < 0:
-            g.start = now + g.start
-
-        g.end = int(request.args.get("end") or 0)
-        if g.end <= 0:
-            g.end = now + g.end
-        g.end = g.end - 60
-
-        g.id = request.args.get("id") or ""
-
-        g.limit = int(request.args.get("limit") or 0)
-        g.page = int(request.args.get("page") or 0)
+from rrd.utils.rrdgraph import graph_history
+from rrd.model.tmpgraph import TmpGraph
 
 @app.route("/chart", methods=["POST",])
 def chart():
@@ -76,16 +16,14 @@ def chart():
     graph_type = request.form.get("graph_type") or GRAPH_TYPE_HOST
 
     id_ = TmpGraph.add(endpoints, counters)
-
     ret = {
-            "ok": False,
-            "id": id_,
-            "params": {
-                "graph_type": graph_type,
-            },
+        "ok": False,
+        "id": id_,
+        "params": {
+            "graph_type": graph_type,
+        },
     }
-    if id_:
-        ret['ok'] = True
+    if id_: ret['ok'] = True
 
     return json.dumps(ret)
 
@@ -106,16 +44,16 @@ def multi_endpoints_chart_data():
     if not g.id:
         abort(400, "no graph id given")
 
-    tmp_graph = TmpGraph.get(g.id)
-    if not tmp_graph:
-        abort(404, "no graph which id is %s" %g.id)
+    j = TmpGraph.get(g.id)
+    if not j:
+        abort(400, "no such tmp_graph where id=%s" %g.id)
 
-    counters = tmp_graph.counters
+    counters = j.counters
     if not counters:
         abort(400, "no counters of %s" %g.id)
     counters = sorted(set(counters))
 
-    endpoints = tmp_graph.endpoints
+    endpoints = j.endpoints
     if not endpoints:
         abort(400, "no endpoints of %s" %(g.id,))
     endpoints = sorted(set(endpoints))
@@ -124,17 +62,11 @@ def multi_endpoints_chart_data():
         "units": "",
         "title": "",
         "series": []
-    }
-    ret['title'] = counters[0]
-    c = counters[0]
-    endpoint_counters = []
-    for e in endpoints:
-        endpoint_counters.append({
-            "endpoint": e,
-            "counter": c,
-        })
+   }
 
-    query_result = graph_query(endpoint_counters, g.cf, g.start, g.end)
+    c = counters[0]
+    ret['title'] = c
+    query_result = graph_history(endpoints, counters[:1], g.cf, g.start, g.end)
 
     series = []
     for i in range(0, len(query_result)):
@@ -147,7 +79,7 @@ def multi_endpoints_chart_data():
                     "cf": g.cf,
                     "endpoint": query_result[i]["endpoint"],
                     "counter": query_result[i]["counter"],
-            }
+                    }
             series.append(serie)
         except:
             pass
@@ -158,7 +90,7 @@ def multi_endpoints_chart_data():
             "cf": g.cf,
             "endpoint": "sum",
             "counter": c,
-    }
+            }
     if g.sum == "on" or g.sumonly == "on":
         sum = []
         tmp_ts = []
@@ -188,16 +120,16 @@ def multi_counters_chart_data():
     if not g.id:
         abort(400, "no graph id given")
 
-    tmp_graph = TmpGraph.get(g.id)
-    if not tmp_graph:
-        abort(404, "no graph which id is %s" %g.id)
+    j = TmpGraph.get(g.id)
+    if not j:
+        abort(400, "no such tmp_graph where id=%s" %g.id)
 
-    counters = tmp_graph.counters
+    counters = j.counters
     if not counters:
         abort(400, "no counters of %s" %g.id)
     counters = sorted(set(counters))
 
-    endpoints = tmp_graph.endpoints
+    endpoints = j.endpoints
     if not endpoints:
         abort(400, "no endpoints of %s" % g.id)
     endpoints = sorted(set(endpoints))
@@ -207,16 +139,10 @@ def multi_counters_chart_data():
         "title": "",
         "series": []
     }
-    ret['title'] = endpoints[0]
     e = endpoints[0]
-    endpoint_counters = []
-    for c in counters:
-        endpoint_counters.append({
-            "endpoint": e,
-            "counter": c,
-        })
+    ret['title'] = e
 
-    query_result = graph_query(endpoint_counters, g.cf, g.start, g.end)
+    query_result = graph_history(endpoints[:1], counters, g.cf, g.start, g.end)
 
     series = []
     for i in range(0, len(query_result)):
@@ -229,7 +155,7 @@ def multi_counters_chart_data():
                     "cf": g.cf,
                     "endpoint": query_result[i]["endpoint"],
                     "counter": query_result[i]["counter"],
-            }
+                    }
             series.append(serie)
         except:
             pass
@@ -240,7 +166,7 @@ def multi_counters_chart_data():
             "cf": g.cf,
             "endpoint": e,
             "counter": "sum",
-    }
+            }
     if g.sum == "on" or g.sumonly == "on":
         sum = []
         tmp_ts = []
@@ -270,16 +196,16 @@ def multi_chart_data():
     if not g.id:
         abort(400, "no graph id given")
 
-    tmp_graph = TmpGraph.get(g.id)
-    if not tmp_graph:
-        abort(404, "no graph which id is %s" %g.id)
+    j = TmpGraph.get(g.id)
+    if not j:
+        abort(400, "no such tmp_graph where id=%s" %g.id)
 
-    counters = tmp_graph.counters
+    counters = j.counters
     if not counters:
         abort(400, "no counters of %s" %g.id)
     counters = sorted(set(counters))
 
-    endpoints = tmp_graph.endpoints
+    endpoints = j.endpoints
     if not endpoints:
         abort(400, "no endpoints of %s, and tags:%s" %(g.id, g.tags))
     endpoints = sorted(set(endpoints))
@@ -290,14 +216,7 @@ def multi_chart_data():
         "series": []
     }
 
-    endpoint_counters = []
-    for e in endpoints:
-        for c in counters:
-            endpoint_counters.append({
-                "endpoint": e,
-                "counter": c,
-            })
-    query_result = graph_query(endpoint_counters, g.cf, g.start, g.end)
+    query_result = graph_history(endpoints, counters, g.cf, g.start, g.end)
 
     series = []
     for i in range(0, len(query_result)):
@@ -310,7 +229,7 @@ def multi_chart_data():
                     "cf": g.cf,
                     "endpoint": "",
                     "counter": "",
-            }
+                    }
             series.append(serie)
         except:
             pass
@@ -321,7 +240,7 @@ def multi_chart_data():
             "cf": g.cf,
             "endpoint": "",
             "counter": "",
-    }
+            }
     if g.sum == "on" or g.sumonly == "on":
         sum = []
         tmp_ts = []
@@ -351,16 +270,16 @@ def charts():
     if not g.id:
         abort(400, "no graph id given")
 
-    tmp_graph = TmpGraph.get(g.id)
-    if not tmp_graph:
-        abort(404, "no graph which id is %s" %g.id)
+    j = TmpGraph.get(g.id)
+    if not j:
+        abort(400, "no such tmp_graph where id=%s" %g.id)
 
-    counters = tmp_graph.counters
+    counters = j.counters
     if not counters:
         abort(400, "no counters of %s" %g.id)
     counters = sorted(set(counters))
 
-    endpoints = tmp_graph.endpoints
+    endpoints = j.endpoints
     if not endpoints:
         abort(400, "no endpoints of %s" %g.id)
     endpoints = sorted(set(endpoints))
@@ -379,7 +298,6 @@ def charts():
     }
 
     if g.graph_type == GRAPH_TYPE_KEY:
-
         for x in endpoints:
             id_ = TmpGraph.add([x], counters)
             if not id_:
@@ -407,4 +325,3 @@ def charts():
             chart_urls.append(src)
 
     return render_template("chart/multi_ng.html", **locals())
-

+ 8 - 8
rrd/view/screen.py

@@ -16,7 +16,7 @@ from rrd import config
 
 @app.route("/screen", methods=["GET", "POST"])
 def dash_screens():
-    top_screens = DashboardScreen.gets(pid='0')
+    top_screens = DashboardScreen.gets_by_pid(pid='0')
     top_screens = sorted(top_screens, key=lambda x:x.name)
 
     return render_template("screen/index.html", **locals())
@@ -80,7 +80,7 @@ def dash_screen(sid):
     start = request.args.get("start")
     end = request.args.get("end")
 
-    top_screens = DashboardScreen.gets(pid=0)
+    top_screens = DashboardScreen.gets_by_pid(pid=0)
     top_screens = sorted(top_screens, key=lambda x:x.name)
 
     screen = DashboardScreen.get(sid)
@@ -88,12 +88,12 @@ def dash_screen(sid):
         abort(404, "no screen")
 
     if str(screen.pid) == '0':
-        sub_screens = DashboardScreen.gets(pid=sid)
+        sub_screens = DashboardScreen.gets_by_pid(pid=sid)
         sub_screens = sorted(sub_screens, key=lambda x:x.name)
         return render_template("screen/top_screen.html", **locals())
 
     pscreen = DashboardScreen.get(screen.pid)
-    sub_screens = DashboardScreen.gets(pid=screen.pid)
+    sub_screens = DashboardScreen.gets_by_pid(pid=screen.pid)
     sub_screens = sorted(sub_screens, key=lambda x:x.name)
     graphs = DashboardGraph.gets_by_screen_id(screen.id)
 
@@ -143,7 +143,7 @@ def dash_screen_add():
 
 @app.route("/screen/<int:sid>/graph", methods=["GET", "POST"])
 def dash_graph_add(sid):
-    all_screens = DashboardScreen.gets()
+    all_screens = DashboardScreen.gets_all()
     top_screens = [x for x in all_screens if x.pid == '0']
     children = []
     for t in top_screens:
@@ -165,10 +165,10 @@ def dash_graph_add(sid):
         counters = counters and counters.split("\n") or []
         counters = [x.strip() for x in counters]
 
-        timespan = request.form.get("timespan", 3600)
+        timespan = int(request.form.get("timespan", 3600))
         graph_type = request.form.get("graph_type", 'h')
         method = request.form.get("method", '').upper()
-        position = request.form.get("position", 0)
+        position = int(request.form.get("position", 0))
 
         graph = DashboardGraph.add(title, hosts, counters, sid,
                 timespan, graph_type, method, position)
@@ -186,7 +186,7 @@ def dash_graph_edit(gid):
     if not graph:
         abort(404, "no graph")
 
-    all_screens = DashboardScreen.gets()
+    all_screens = DashboardScreen.gets_all()
     top_screens = [x for x in all_screens if x.pid == '0']
     children = []
     for t in top_screens: