Completed
Push — master ( 05f124...f2ad1f )
by Roy
01:15
created

counter()   B

Complexity

Conditions 6

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
dl 0
loc 19
rs 8
c 0
b 0
f 0
1
#!/usr/bin/env python
2
# -*- encoding: utf-8 -*-
3
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
4
# Author: Binux<[email protected]>
5
#         http://binux.me
6
# Created on 2014-02-22 23:20:39
7
8
import socket
9
10
from six import iteritems, itervalues
11
from flask import render_template, request, json
12
from flask.ext import login
13
from .app import app
14
15
index_fields = ['name', 'group', 'status', 'comments', 'rate', 'burst', 'updatetime']
16
17
18
@app.route('/')
19
def index():
20
    projectdb = app.config['projectdb']
21
    projects = sorted(projectdb.get_all(fields=index_fields),
22
                      key=lambda k: (0 if k['group'] else 1, k['group'], k['name']))
23
    return render_template("index.html", projects=projects)
24
25
26
@app.route('/queues')
27
def get_queues():
28
    def try_get_qsize(queue):
29
        if queue is None:
30
            return 'None'
31
        try:
32
            return queue.qsize()
33
        except Exception as e:
34
            return "%r" % e
35
36
    result = {}
37
    queues = app.config.get('queues', {})
38
    for key in queues:
39
        result[key] = try_get_qsize(queues[key])
40
    return json.dumps(result), 200, {'Content-Type': 'application/json'}
41
42
43
@app.route('/update', methods=['POST', ])
44
def project_update():
45
    projectdb = app.config['projectdb']
46
    project = request.form['pk']
47
    name = request.form['name']
48
    value = request.form['value']
49
50
    project_info = projectdb.get(project, fields=('name', 'group'))
51
    if not project_info:
52
        return "no such project.", 404
53
    if 'lock' in projectdb.split_group(project_info.get('group')) \
54
            and not login.current_user.is_active():
55
        return app.login_response
56
57
    if name not in ('group', 'status', 'rate'):
58
        return 'unknown field: %s' % name, 400
59
    if name == 'rate':
60
        value = value.split('/')
61
        if len(value) != 2:
62
            return 'format error: rate/burst', 400
63
        rate = float(value[0])
64
        burst = float(value[1])
65
        update = {
66
            'rate': min(rate, app.config.get('max_rate', rate)),
67
            'burst': min(burst, app.config.get('max_burst', burst)),
68
        }
69
    else:
70
        update = {
71
            name: value
72
        }
73
74
    ret = projectdb.update(project, update)
75
    if ret:
76
        rpc = app.config['scheduler_rpc']
77
        if rpc is not None:
78
            try:
79
                rpc.update_project()
80
            except socket.error as e:
81
                app.logger.warning('connect to scheduler rpc error: %r', e)
82
                return 'rpc error', 200
83
        return 'ok', 200
84
    else:
85
        return 'update error', 500
86
87
88
@app.route('/counter')
89
def counter():
90
    rpc = app.config['scheduler_rpc']
91
    if rpc is None:
92
        return json.dumps({})
93
94
    result = {}
95
    try:
96
        data = rpc.webui_update()
97
        for type, counters in iteritems(data['counter']):
98
            for project, counter in iteritems(counters):
99
                result.setdefault(project, {})[type] = counter
100
        for project, paused in iteritems(data['pause_status']):
101
            result.setdefault(project, {})['paused'] = paused
102
    except socket.error as e:
103
        app.logger.warning('connect to scheduler rpc error: %r', e)
104
        return json.dumps({}), 200, {'Content-Type': 'application/json'}
105
106
    return json.dumps(result), 200, {'Content-Type': 'application/json'}
107
108
109
@app.route('/run', methods=['POST', ])
110
def runtask():
111
    rpc = app.config['scheduler_rpc']
112
    if rpc is None:
113
        return json.dumps({})
114
115
    projectdb = app.config['projectdb']
116
    project = request.form['project']
117
    project_info = projectdb.get(project, fields=('name', 'group'))
118
    if not project_info:
119
        return "no such project.", 404
120
    if 'lock' in projectdb.split_group(project_info.get('group')) \
121
            and not login.current_user.is_active():
122
        return app.login_response
123
124
    newtask = {
125
        "project": project,
126
        "taskid": "on_start",
127
        "url": "data:,on_start",
128
        "process": {
129
            "callback": "on_start",
130
        },
131
        "schedule": {
132
            "age": 0,
133
            "priority": 9,
134
            "force_update": True,
135
        },
136
    }
137
138
    try:
139
        ret = rpc.newtask(newtask)
140
    except socket.error as e:
141
        app.logger.warning('connect to scheduler rpc error: %r', e)
142
        return json.dumps({"result": False}), 200, {'Content-Type': 'application/json'}
143
    return json.dumps({"result": ret}), 200, {'Content-Type': 'application/json'}
144
145
146
@app.route('/robots.txt')
147
def robots():
148
    return """User-agent: *
149
Disallow: /
150
Allow: /$
151
Allow: /debug
152
Disallow: /debug/*?taskid=*
153
""", 200, {'Content-Type': 'text/plain'}
154