~openerp-dev/openobject-client-web/trunk-improvement_title-ssu

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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#!/usr/bin/python

import cgitb,optparse,os,re,subprocess,sys,time

import launchpadlib.launchpad,mako.template

#----------------------------------------------------------
# OpenERP rdtools utils
#----------------------------------------------------------

def log(*l,**kw):
    out=[time.strftime("%Y-%m-%d %H:%M:%S")]
    for i in l:
        if not isinstance(i,basestring):
            i=repr(i)
        out.append(i)
    out+=["%s=%r"%(k,v) for k,v in kw.items()]
    print " ".join(out)

def lock(name):
    fd=os.open(name,os.O_CREAT|os.O_RDWR,0600)
    fcntl.lockf(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)

def nowait():
    signal.signal(signal.SIGCHLD, signal.SIG_IGN)

def run(l):
    log("run",*l)
    if isinstance(l,list):
        rc=os.spawnvp(os.P_WAIT, l[0], l)
    elif isinstance(l,str):
        tmp=['sh','-c',l]
        rc=os.spawnvp(os.P_WAIT, tmp[0], tmp)
    return rc

def kill(pid,sig=9):
    try:
        os.kill(pid,sig)
    except OSError:
        pass

def underscorize(n):
    return n.replace("~","").replace(":","_").replace("/","_")

#----------------------------------------------------------
# OpenERP RunBot
#----------------------------------------------------------

class RunBotBranch(object):
    def __init__(self,runbot,branch):
        self.runbot=runbot
        self.running=False
        self.running_port=None
        self.running_server_pid=None
        self.running_web_pid=None
        self.running_t0=None
        self.date_last_modified=0
        self.revision_count=0
        self.merge_count=0

        self.name=branch.name
        self.unique_name=branch.unique_name
        self.project_name=re.search("/openobject-(addons|server|client-web)/",self.unique_name).group(1)
        self.uname=underscorize(self.unique_name)

        self.repo_path=os.path.join(self.runbot.wd,'repo',self.uname)
        self.subdomain="%s-%s"%(self.project_name,self.name.replace('_','-'))
        self.running_path=os.path.join(self.runbot.wd,'running',self.subdomain)

        self.server_path=os.path.join(self.running_path,"server")
        self.server_bin_path=os.path.join(self.server_path,"openerp-server.py")

        self.web_path=os.path.join(self.running_path,"web")
        self.web_bin_path=os.path.join(self.web_path,"openerp-web.py")

        self.log_path=os.path.join(self.runbot.wd,'static','logs',self.subdomain)
        self.log_server_path=os.path.join(self.runbot.wd,'static','logs',self.subdomain,'server.txt')
        self.log_web_path=os.path.join(self.runbot.wd,'static','logs',self.subdomain,'client-web.txt')

    def update(self,branch):
        log("branch-update",branch=self.unique_name)
        if self.revision_count != branch.revision_count:
            if os.path.exists(self.repo_path):
                run(["bzr","pull","-d",self.repo_path,"--overwrite"])
            else:
                run(["bzr","branch","lp:%s"%self.unique_name,self.repo_path])
            self.date_last_modified=branch.date_last_modified
            self.revision_count=branch.revision_count
            self.merge_count=len(list(branch.getMergeProposals()))
            return True

    def start(self,port):
        log("branch-start",branch=self.unique_name,port=port)
        server_src = os.path.join(self.runbot.wd,'repo','openerp_openobject-server_trunk')
        addons_src = os.path.join(self.runbot.wd,'repo','openerp_openobject-addons_trunk')
        web_src = os.path.join(self.runbot.wd,'repo','openerp_openobject-client-web_trunk')
        if self.project_name == "server":
            server_src = self.repo_path
        if self.project_name == "addons":
            addons_src = self.repo_path
        if self.project_name == "client-web":
            web_src = self.repo_path
        for i in [self.running_path,self.log_path]:
            if not os.path.exists(i):
                os.makedirs(i)
        run(["rsync","-a","--exclude",".bzr","--delete","%s/"%server_src,self.server_path])
        run(["rsync","-a","--exclude",".bzr","%s/"%addons_src,os.path.join(self.server_path,"openerp/addons")])
        run(["rsync","-a","--exclude",".bzr","--delete","%s/"%web_src,self.web_path])
        run(["dropdb",self.subdomain])
        run(["createdb",self.subdomain])

        out=open(self.log_server_path,"w")
        cmd=[self.server_bin_path,"-d",self.subdomain,"-i","base","--no-xmlrpc","--no-xmlrpcs","--netrpc-port=%d"%(self.runbot.server_port+port)]
        log("run",*cmd,log=self.log_server_path)
        p=subprocess.Popen(cmd, stdout=out, stderr=out, close_fds=True)
        self.running_server_pid=p.pid

        config="""
        [global]
        server.environment = "development"
        server.socket_host = "0.0.0.0"
        server.socket_port = %d
        server.thread_pool = 10
        tools.sessions.on = True
        log.access_level = "INFO"
        log.error_level = "INFO"
        tools.csrf.on = False
        tools.log_tracebacks.on = False
        tools.cgitb.on = True
        openerp.server.host = 'localhost'
        openerp.server.port = '%d'
        openerp.server.protocol = 'socket'
        openerp.server.timeout = 450
        [openerp-web]
        dblist.filter = 'BOTH'
        dbbutton.visible = True
        company.url = ''
        """%(self.runbot.web_port+port,self.runbot.server_port+port)
        config=config.replace("\n        ","\n")
        open(os.path.join(self.web_path,"doc","openerp-web.cfg"),"w").write(config)

        out=open(self.log_web_path,"w")
        cmd=[self.web_bin_path]
        log("run",*cmd,log=self.log_web_path)
        p=subprocess.Popen(cmd, stdout=out, stderr=out, close_fds=True)
        self.running_web_pid=p.pid

        self.runbot.running.insert(0,self)
        self.runbot.running.sort(key=lambda x:x.date_last_modified,reverse=1)
        self.running=True
        self.running_t0=time.time()
        self.running_port=port

    def stop(self):
        log("branch-stop",branch=self.unique_name,port=self.running_port)
        kill(self.running_server_pid)
        kill(self.running_web_pid)
        self.runbot.running.remove(self)
        self.running=False
        self.running_port=None

class RunBot(object):
    def __init__(self,wd,team,poll,server_port,web_port,number,nginx_port,domain):
        self.wd=wd
        self.sleeptime=poll
        self.team=team
        self.server_port=int(server_port)
        self.web_port=int(web_port)
        self.number=int(number)
        self.nginx_port=int(nginx_port)
        self.domain=domain
        self.branches={}
        self.running=[]

    def nginx_reload(self):
        nginx_pid_path = os.path.join(self.wd,'nginx','nginx.pid')
        if os.path.isfile(nginx_pid_path):
            pid=int(open(nginx_pid_path).read())
            os.kill(pid,1)
        else:
            run(["nginx","-p",self.wd,"-c",os.path.join(self.wd,"nginx/nginx.conf")])

    def nginx_config(self):
        template="""
        pid nginx/nginx.pid;
        error_log nginx/error.log;
        worker_processes  1;
        events { worker_connections  1024; }
        http {
          server_names_hash_bucket_size 128;
          autoindex on;
          client_body_temp_path nginx; proxy_temp_path nginx; fastcgi_temp_path nginx; access_log nginx/access.log; index index.html;
          server { listen ${r.nginx_port} default; server_name _; root ./static; }
          % for i in r.running:
             server {
                listen ${r.nginx_port};
                server_name ${i.subdomain}.${r.domain};
                location / { proxy_pass http://127.0.0.1:${r.web_port+i.running_port}; proxy_set_header X-Forwarded-Host $host; }
             }
          % endfor
        }
        """
        return mako.template.Template(template).render(r=self)

    def nginx_index_time(self,t):
        for m,u in [(86400,'d'),(3600,'h'),(60,'m')]:
            if t>=m:
                return str(int(t/m))+u
        return str(int(t))+"s"

    def nginx_index(self):
        template = """<!DOCTYPE html>
        <html>
        <head>
        <style type="text/css">
        a { text-decoration : none; }
        </style>
        </head>
        <body>
        <h2>OpenERP runbot (${r.team})</h2>
        <table cellspacing="0" cellpadding="3" border="1">
        <tr>
            <th>Branch</th>
            <th>Date</th>
            <th>Logs</th>
            <th>LP revno</th>
            <th>LP bug</th>
            <th>LP merge</th>
        </tr>
        % for i in r.running:
        <tr valign="top">
            <td>
                <a href="http://${i.subdomain}.${r.domain}/" style="font-weight:bold;">${i.subdomain}</a> <small>(netrpc: ${r.server_port+i.running_port})</small>
                <br>
                bzr branch <a href="https://code.launchpad.net/${i.unique_name}">lp:${i.unique_name}</a>
            </td>
            <td>
                ${i.date_last_modified.strftime("%Y-%m-%d %H:%M:%S")}<br>
                running time 
                % if t-i.running_t0 < 120:
                    <span style="color:red;">${r.nginx_index_time(t-i.running_t0)}</span>
                % else:
                    <span style="color:green;">${r.nginx_index_time(t-i.running_t0)}</span>
                % endif
            </td>
            <td>
                <a href="http://${r.domain}/logs/${i.subdomain}/server.txt">server</a>
                <a href="http://${r.domain}/logs/${i.subdomain}/client-web.txt">web</a>
            </td>
            <td> <a href="http://bazaar.launchpad.net/${i.unique_name}/revision/${i.revision_count}">${i.revision_count}</a> </td>
            <td>
            <% bug=re.search('bug-([0-9]+)-',i.subdomain) %>
            % if bug:
                <a href="https://bugs.launchpad.net/bugs/${bug.group(1)}">Bug ${bug.group(1)}</a>
            % else:
                /
            % endif
            </td>
            <td>
            % if i.merge_count:
                <a href="https://code.launchpad.net/${i.unique_name}/+activereviews">${i.merge_count} pending</a>
            % else:
                /
            % endif
            </td>
        </tr>
        % endfor
        </table>
        </body>
        """
        return mako.template.Template(template).render(r=self,t=time.time(),re=re)

    def nginx_udpate(self):
        log("runbot-nginx-update")
        f=open(os.path.join(self.wd,'static','index.html'),"w")
        f.write(self.nginx_index())
        f.close()
        f=open(os.path.join(self.wd,'nginx','nginx.conf'),"w")
        f.write(self.nginx_config())
        f.close()
        self.nginx_reload()

    def allocate_port_and_run(self,rbb):
        if len(self.running) >= self.number:
            victim = self.running[-1]
            victim.stop()
        running_ports=[i.running_port for i in self.running]
        for p in range(self.number):
            if p not in running_ports:
                break
        rbb.start(p)
        self.nginx_udpate()

    def process(self):
        log("runbot-process")
        launchpad=launchpadlib.launchpad.Launchpad.login_anonymously('openerp-runbot', 'edge', 'lpcache')
        trunk_branches = [
            launchpad.branches.getByUniqueName(unique_name="~openerp/openobject-server/trunk"),
            launchpad.branches.getByUniqueName(unique_name="~openerp/openobject-addons/trunk"),
            launchpad.branches.getByUniqueName(unique_name="~openerp/openobject-client-web/trunk"),
        ]
        for b in trunk_branches:
            RunBotBranch(self,b).update(b)
        team=launchpad.people[self.team]
        team_branches=team.getBranches()
        branches_sorted=[(b.date_last_modified,b) for b in team_branches if re.search("/openobject-(addons|server|client-web)/",b.unique_name)]
        branches_sorted.sort(reverse=1)
        branches=trunk_branches+[b[1] for b in branches_sorted]
        for b in branches[:self.number]:
            rbb=self.branches.setdefault(b.unique_name,RunBotBranch(self,b))
            updated=rbb.update(b)
            if updated:
                if rbb.running:
                    rbb.stop()
                self.allocate_port_and_run(rbb)
        self.nginx_udpate()

    def loop(self):
        while 1:
            try:
                self.process()
                log("runbot-sleep",self.sleeptime)
                time.sleep(self.sleeptime)
            except Exception,e:
                log("runbot-exception")
                print cgitb.text(sys.exc_info())
            except KeyboardInterrupt,e:
                log("sigint recevied exiting...")
                for i in self.running:
                    i.stop()
                raise e

def runbot_init(wd):
    dest = os.path.join(wd,'repo')
    if not os.path.exists(dest):
        run(["bzr","init-repo",dest])
    for i in ['nginx','static','running','lpcache']:
        dest = os.path.join(wd,i)
        if not os.path.exists(dest):
            os.mkdir(dest)
    run('sudo su - postgres -c "createuser -s $USER"')

def main():

    os.chdir(os.path.normpath(os.path.dirname(__file__)))
    parser = optparse.OptionParser(usage="%prog [--runbot-init|--runbot-run] [options] ",version="1.0")
    parser.add_option("--runbot-init", action="store_true", help="initialize the runbot environment")
    parser.add_option("--runbot-run", action="store_true", help="run the runbot")
    parser.add_option("--runbot-dir", metavar="DIR", default=".", help="runbot working dir (%default)")
    parser.add_option("--runbot-team", metavar="TEAM", default="openerp-dev", help="launchpad team to monitor (%default)")
    parser.add_option("--runbot-server-port", metavar="PORT", default=9100, help="starting port for servers (%default)")
    parser.add_option("--runbot-web-port", metavar="PORT", default=9200, help="starting port for client-web (%default)")
    parser.add_option("--runbot-nginx-port", metavar="PORT", default=9000, help="starting port for nginx server (%default)")
    parser.add_option("--runbot-nginx-domain", metavar="DOMAIN", default="runbot.openerp.com", help="virtual host domain (%default)")
    parser.add_option("--runbot-number", metavar="NUMBER", default=5, help="max concurrent instance to run (%default)")
    parser.add_option("--runbot-poll", metavar="SECONDS", default=300, help="launchpad polling interval (%default)")
    o, a = parser.parse_args(sys.argv)
    if o.runbot_init:
        runbot_init(o.runbot_dir)
    elif o.runbot_run:
        r = RunBot(o.runbot_dir,o.runbot_team,o.runbot_poll,o.runbot_server_port,o.runbot_web_port,o.runbot_number,o.runbot_nginx_port,o.runbot_nginx_domain)
        r.loop()
    else:
        parser.print_help()

if __name__ == '__main__':
    print "kill ` ps faux | grep ./running  | awk '{print $2}' `"
    main()