~loyalinfo/openerp-tools/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""
Runbot dynamic web server, to handle stickiness changes, build command and
teams and branches registration.
"""
import os
import simplejson
import threading
import urllib
import urlparse
import sys

import openerprunbot

import logging
_logger = logging.getLogger(__name__)
runbot_state_lock = threading.Lock()

httpd = None

def serve(port):
    """ Serve HTTP requests via werkzeug development server.

    If werkzeug can not be imported, we fall back to wsgiref's simple_server.

    Calling this function is blocking, you might want to call it in its own
    thread.
    """

    global httpd

    interface = '127.0.0.1'
    try:
        import werkzeug.serving
        httpd = werkzeug.serving.make_server(interface, port, application, threaded=True)
        openerprunbot.misc.log('HTTP service (werkzeug) running on %s:%s' % (interface, port))
    except ImportError, e:
        import wsgiref.simple_server
        httpd = wsgiref.simple_server.make_server(interface, port, application)
        openerprunbot.misc.log('HTTP service (wsgiref) running on %s:%s' % (interface, port))

    try:
        httpd.serve_forever()
    except Exception:
        _logger.exception('Cannot serve on %s:%s', interface, port)
        # TODO clean jobs?
        sys.exit(1)

def start_server(port):
    """ Call serve() in its own thread.

    The WSGI server can be shutdown with stop_server() below.
    """
    threading.Thread(name='http', target=serve, args=(port,)).start()

def stop_server():
    """ Initiate the shutdown of the WSGI server.

    The server is supposed to have been started by start_server() above.
    """
    if httpd:
        httpd.shutdown()

def read_state():
    with runbot_state_lock:
        try:
            path = os.path.join('static', 'state.runbot')
            if os.path.exists(path):
                with open(path, 'r') as f:
                    state = simplejson.loads(f.read())
                    openerprunbot.state = state
        except Exception, e:
            print "Exception in read_state(): ", e

# TODO lock
def _with_state(f):
    state = {}
    path = os.path.join('static', 'state.runbot')

    with runbot_state_lock:
        if os.path.exists(path):
            with open(path, 'r') as h:
                state = simplejson.loads(h.read())

        f(state)

        with open(path, 'w') as h:
            data = simplejson.dumps(state, sort_keys=True, indent=4)
            h.write(data)

    # Replace the whole dictionary at once.
    openerprunbot.state = state

def _delete(team, group):
    if team == 'openerp-dev' and group in openerprunbot.core.SERIES_BRANCHES:
        print 'delete', team, group, "ignored (core group)"
        return
    group_id = (team, group)
    group = openerprunbot.runbot.groups.get(group_id)
    if group:
        if group.is_sticky():
            print 'delete', team, group, "ignored (sticky)"
            return
        print 'delete', team, group
        del openerprunbot.runbot.groups[group_id]
        for j in group.points:
            j.stop()
        def f(state):
            # TODO check team and group are valid
            state.setdefault(team, {})
            state[team].pop(group, None)
            if not state[team]:
                del state[team]
        _with_state(f)

def _stick(team, group):
    print 'stick', team, group
    def f(state):
        # TODO check team and group are valid
        state.setdefault(team, {})
        state[team].setdefault(group, {})
        state[team][group]['sticky'] = True
    _with_state(f)

def _unstick(team, group):
    print 'unstick', team, group
    def f(state):
        # TODO check team and group are valid
        state.setdefault(team, {})
        state[team].setdefault(group, {})
        if 'sticky' in state[team][group]:
            del state[team][group]['sticky']
        if not state[team][group]:
            del state[team][group]
        if not state[team]:
            del state[team]
    _with_state(f)

def _build(team, group):
    print 'build', team, group
    openerprunbot.queue.put(('build', (team, group)))

def _register_branch(team, project, group):
    print 'register branch', team, project, group
    def f(state):
        # TODO check team and group are valid
        state.setdefault('registered-branches', [])
        state['registered-branches'].append("~%s/%s/%s" % (team, project, group))
    _with_state(f)

def _register_team(team):
    print 'register team'
    def f(state):
        # TODO check team is valid
        state.setdefault('registered-teams', []) # TODO must be a {}
        state['registered-teams'].append(team)
    _with_state(f)

def _configure_group(team_name=None, name=None, version=None, server_branch=None,
        client_web_branch=None, web_branch=None, addons_branch_0=None,
        addons_branch_1=None, addons_branch_2=None, modules=None):
    print 'configure group'
    addons_branches = []
    for i in (addons_branch_0, addons_branch_1, addons_branch_2):
        if i:
            addons_branches.append(i)
    def f(state):
        # TODO check team is valid
        state.setdefault('configured-branches', {})
        state['configured-branches'].setdefault(team_name, {})
        state['configured-branches'][team_name].setdefault(name, {})
        state['configured-branches'][team_name][name] = dict(
            version=version,
            server_branch=server_branch,
            client_web_branch=client_web_branch,
            web_branch=web_branch,
            addons_branches=addons_branches,
            modules=modules,
        )
    _with_state(f)


def application(environ, start_response):
    def send_notice(message):
        response = openerprunbot.templates.render_template('notice.html.mako', message=message)
        start_response('200 OK', [('Content-Type', 'text/html'), ('Content-Length', str(len(response)))])
        return [response]

    if environ['REQUEST_METHOD'] == 'GET' and environ['PATH_INFO'].startswith('/hostname/'):
        hostname = environ['PATH_INFO'][len('/hostname/'):]
        response = openerprunbot.runbot.get_by_host(hostname)
        start_response('200 OK', [('Content-Type', 'application/json'), ('Content-Length', str(len(response)))])
        return [response]

    if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'] == ('/a/branch'):
        length = int(environ['CONTENT_LENGTH'])
        data = urllib.unquote(environ['wsgi.input'].read(length))
        data_ = urlparse.parse_qs(data).get('branch-input',[''])[0]
        m = openerprunbot.branch_input_re.match(data_)
        if m:
            team_name = m.group(1)
            project = m.group(2)
            branch_name = m.group(3)
            _register_branch(team_name, project, branch_name)
            response = data_ + ' is registered. It will be picked by the Runbot at the next build iteration (about every two minutes).'
            return send_notice(response)

    if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'] == ('/a/team'):
        length = int(environ['CONTENT_LENGTH'])
        data = urllib.unquote(environ['wsgi.input'].read(length))
        data_ = urlparse.parse_qs(data).get('team-input',[''])[0]
        if data_:
            _register_team(data_)
            response = data_ + ' is registered. It will be picked by the Runbot at the next build iteration (about every two minutes).'
            return send_notice(response)

    if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'] == ('/a/configure-build'):
        length = int(environ['CONTENT_LENGTH'])
        data = urllib.unquote(environ['wsgi.input'].read(length))
        data_ = {}
        for n in (
            "team_name", "name", "version", "server_branch",
            "client_web_branch", "web_branch",
            "addons_branch_0", "addons_branch_1", "addons_branch_2", "modules"):
            data_[n] = urlparse.parse_qs(data).get(n,[''])[0]
        if (data_['version'] in openerprunbot.core.SERIES_BRANCHES) and \
            data_['team_name'] and \
            data_['name'] and \
            data_['server_branch'] and \
            (data_['web_branch'] or data_['client_web_branch']) and \
            data_['addons_branch_0']:
            _configure_group(**data_)
            response = data_['name'] + ' is registered. It will be picked by the Runbot at the next build iteration (about every two minutes).'
            return send_notice(response)

    if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'] == ('/a'):
        query = urlparse.parse_qs(environ['QUERY_STRING'])

        if query.get('team'):
            team = query['team'][0]

            if query.get('deletegroup'):
                group = query['deletegroup'][0]
                _delete(team, group)
                response = group + ' is gone forever!'
                return send_notice(response)

            if query.get('stick'):
                group = query['stick'][0]
                _stick(team, group)
                response = group + ' is now sticky'
                return send_notice(response)

            if query.get('unstick'):
                group = query['unstick'][0]
                _unstick(team, group)
                response = group + ' is now non-sticky'
                return send_notice(response)

            if query.get('build'):
                group = query['build'][0]
                _build(team, group)
                response = '`' + group + '` will be built.'
                return send_notice(response)

    message = 'Are you lost?\n\n\n(^____^)\n'
    response = openerprunbot.templates.render_template('notice.html.mako', message=message)
    start_response('404 Not Found', [('Content-Type', 'text/html'), ('Content-Length', str(len(response)))])
    return [response]

if __name__ == '__main__':
   serve(8999)