summaryrefslogtreecommitdiffstats
path: root/qabox/fedpkg-autobuilder
blob: 2139172ea3933f25f6e25dcb80518ee44ef9e1f0 (plain)
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
#!/usr/bin/python

# fedpkg-autobuilder:
# Daemon which runs fedpkg-pull-build-chain continually.
#
# Licensed under the new-BSD license (http://www.opensource.org/licenses/bsd-license.php)
# Copyright (C) 2010 Red Hat, Inc.
# Written by Colin Walters <walters@verbum.org>

import getopt
import os
import sys
import subprocess
import shutil
import logging
import xml.dom.minidom
import ConfigParser

import dbus, dbus.service
import glib
import gobject
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)

PULLBUILD_SERVICE = 'org.fedoraproject.FedpkgPullBuildChain'
PULLBUILD_OBJPATH = '/org/fedoraproject/FedpkgPullBuildChain'

# First ensure we have a bus
if not 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
    print "FATAL: Must have DBUS_SESSION_BUS_ADDRESS in environment"
    sys.exit(1)

def check_call_verbose(*args, **kwargs):
    print "Running: %r" % (args[0], )
    subprocess.check_call(*args, **kwargs)
    
STATE_BURNING = 'burning'
STATE_SUCCESS = 'success'

STATUS_ACTIVE = 'active'
STATUS_IDLE = 'idle'

class ReleaseBuilder(gobject.GObject):
    __gsignals__ = {
        'changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, [])
    }

    def __init__(self, name, config):
        gobject.GObject.__init__(self)
        self.name = name

        self._config = config

        self.status = STATUS_IDLE
        self.statusdata = {}
        
        self._resultdir = config.get(name, 'resultdir')
        self._release = name     
        
        self._builder_bus_name = '%s.%s' % (PULLBUILD_SERVICE, self._release.replace('-', '_'))
        
        try:
            self._architectures = self._get_option('architectures').split()
        except ConfigParser.NoOptionError, e:
            self._architectures = None

        modules = self._get_option('modules')
        self._modules = modules.split()
        
        self._pullbuild_pid = None
        self._pullbuild_proxy = None
        
        bus = dbus.SessionBus()
        self._bus_proxy = dbus.Interface(bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus'),
                                         'org.freedesktop.DBus')
        self._bus_proxy.connect_to_signal('NameOwnerChanged', self.__on_name_owner_changed)

    def _get_option(self, key):
        try:
            return self._config.get(self.name, key)
        except ConfigParser.NoOptionError, e:
            return self._config.get('build', key)
            
    def __on_name_owner_changed(self, name, prev_owner, new_owner):
        if name != self._builder_bus_name:
            return
        if new_owner == '':
            del self._pullbuild_proxy
            self._pullbuild_proxy = None
            return
        logging.debug("NameOwnerChanged %r %r %r" % (name, prev_owner, new_owner))
        bus = dbus.SessionBus()
        proxy = bus.get_object(PULLBUILD_SERVICE, PULLBUILD_OBJPATH)
        self._pullbuild_proxy = dbus.Interface(proxy, PULLBUILD_SERVICE)
        self._pullbuild_proxy.connect_to_signal('StateChanged', self.__on_builder_state_changed)

    def __on_builder_state_changed(self, state, statedata):
        logging.info("builder state=%s statedata=%r" % (state, statedata))
        self.statusdata = dict(statedata)
        self.emit('changed')
        
    def __on_builder_exited(self, pid, condition):
        logging.info("builder pid=%d exited, condition=%r", pid, condition)
        self._pullbuild_pid = None
        self.status = STATUS_IDLE
        self.statusdata = {}
        
    def start(self, force):
        if self._pullbuild_pid is not None:
            return
        args = ['fedpkg-pull-build-chain', '--resultdir=' + self._resultdir, '--release=' + self._release]
        if force:
            args.append('--force')
        if self._architectures is not None:
            for arch in self._architectures:
                args.append('--arch=' + arch)
                
        args.extend(self._modules)
        
        (self._pullbuild_pid, _, _, _) = glib.spawn_async(args, flags=glib.SPAWN_DO_NOT_REAP_CHILD|glib.SPAWN_SEARCH_PATH)
        logging.info("started builder, pid=%d" % (self._pullbuild_pid, ))
        self.status = STATUS_ACTIVE
        self.statusdata = {}
        self.emit('changed')
        glib.child_watch_add(self._pullbuild_pid, self.__on_builder_exited)

class Autobuilder(dbus.service.Object):
    def __init__(self, config):
        dbus.service.Object.__init__(self, dbus.SessionBus(), '/org/fedoraproject/FedpkgAutoBuilder')
        self._config = config
        
        self._releases = config.get('build', 'releases')
        self._builders = []
        for release in self._releases.split():
            builder = ReleaseBuilder(release, config)
            self._builders.append(builder)

    @dbus.service.method(dbus_interface='org.fedoraproject.FedpkgAutoBuilder',
                         in_signature='', out_signature='a{sv}')
    def GetState(self):
        result = {}
        for builder in self._builders:
            if builder.status == STATUS_ACTIVE:
                status_str = 'active'
            else:
                status_str = 'idle'
            result[builder.name] = {'status': status_str }
        return result
  
    @dbus.service.method(dbus_interface='org.fedoraproject.FedpkgAutoBuilder',
                         in_signature='b', out_signature='s')
    def Build(self, force):
        for builder in self._builders:
            builder.start(force)
        return repr(self.GetState())
    
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], '', ['conf='])
    except Getopt.GetoptError, e:
        print unicode(e)
        print "Usage: fedpkg-autobuilder --conf=file.conf"
    
    conf = None
    for o, a in opts:
        if o in ('-c', '--conf'):
            conf = a
    
    if not conf:
        print "Must specify --conf=file.conf"
        sys.exit(1)
    
    logging.basicConfig(level=logging.INFO)
    
    parser = ConfigParser.SafeConfigParser()
    parser.read(conf)
    build_time = int(parser.get('autobuild', 'time'))
    
    f = open('session-address', 'w')
    f.write(os.environ['DBUS_SESSION_BUS_ADDRESS'])
    f.close()
    bus = dbus.SessionBus()
    bus_name = dbus.service.BusName('org.fedoraproject.FedpkgAutoBuilder', bus=bus)

    loop = gobject.MainLoop()
    
    builder = Autobuilder(parser)
    builder.Build(False)
    glib.timeout_add(build_time * 1000, lambda: builder.Build(False) or True)
    
    loop.run()
    
if __name__ == '__main__':
    main()