summaryrefslogtreecommitdiffstats
path: root/fedpkg-pull-build-chain
blob: f72acffe6e7ed939e5dae22ce64a03adc99e0ee2 (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
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
#!/usr/bin/python

# fedpkg-pull-build-chain:
# Build binary RPMS for the named source RPMs from the latest upstream code.  Fedora CVS tree
# is checked out into the current directory.  Build logs go in _build.  You must specify
# a destination path for RPMS with --resultdir.
#
# 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 dbus, dbus.service, dbus.bus
import glib
import gobject
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)

def check_call_verbose(*args, **kwargs):
    print "Running: %r" % (args[0], )
    subprocess.check_call(*args, **kwargs)

def popen_verbose(*args, **kwargs):
    print "Running: %r" % (args[0], )
    return subprocess.Popen(*args, **kwargs)

STATE_STARTING = 'starting'
STATE_VCS = 'vcs'
STATE_BUILDING = 'building'

class FedpkgPullBuildChainState(dbus.service.Object):
    def __init__(self, path):
        dbus.service.Object.__init__(self, dbus.SessionBus(), path)
        
    @dbus.service.signal(dbus_interface='org.fedoraproject.FedpkgPullBuildChain',
                         signature='sa{sv}')
    def StateChanged(self, state, statedata):
        pass

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], '', ['release=', 'arch=', 'resultdir=', 'delete-old', 'force'])
    except getopt.GetoptError, e:
        print unicode(e)
        print "Usage: fedpkg-pull-build-chain --release=F-12 --resultdir=/path/to/repo rpm1 rpm2 ..."
        sys.exit(1)
        
    if 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
        bus = dbus.SessionBus()
        bus_name = dbus.service.BusName('org.fedoraproject.FedpkgPullBuildChain', bus=bus)
        state_notifier = FedpkgPullBuildChainState('/org/fedoraproject/FedpkgPullBuildChain')
        state_notifier.StateChanged
    else:
        state_notifier = None
        
    def notify_state(state, statedata):
        if not state_notifier:
            return
        state_notifier.StateChanged(state, statedata)
        dbus.SessionBus().flush()
        
    force = False
    delete_old = False
    release = None
    resultdir = None
    architectures = []
    for o, a in opts:
        if o in ('--force', ):
            force = True
        elif o in ('--release', ):
            release = a
        elif o in ('--arch', ):
            architectures.append(a)
        elif o in ('--resultdir', ):
            resultdir = a
        elif o in ('--delete-old', ):
            delete_old = True

    if release is None:
        print "Must specify --release"
        sys.exit(1)
    if resultdir is None:
        print "Must specify --resultdir=/path/to/repository"
        sys.exit(1)
            
    if len(architectures) == 0:
        architectures.append(subprocess.Popen(['uname', '-m'], stdout=subprocess.PIPE).communicate()[0].strip())
        
    if not os.path.exists(resultdir):
        print "Creating repository in %r" % (resultdir, )
        os.mkdir(resultdir)
        check_call_verbose(['createrepo', '.'], cwd=resultdir)
        
    try:
        os.mkdir('_build')
    except OSError, e:
        pass
        
    mockreleases = []
    for f in ('site-defaults.cfg', 'logging.ini'):
        shutil.copy2('/etc/mock/' + f, '_build')

    for architecture in architectures:
        # FIXME do this better
        mockrelease = 'fedora-' + release[2:].lower() + '-' + architecture
        f_in = open(os.path.join('/etc', 'mock', mockrelease + '.cfg'))
        new_mockrelease_path = os.path.join('_build', mockrelease + '.cfg')
        f_out = open(new_mockrelease_path, 'w')
        for line in f_in:
            f_out.write(line)
        f_in.close()
        f_out.write('config_opts[\'yum.conf\'] += """[buildchain]\nname=buildchain\nbaseurl=file://%s\n"""' % (os.path.abspath(resultdir), ))
        f_out.close()
        mockreleases.append(mockrelease)
       
    failed = []
    for arg in args:
        if not os.path.isdir(arg):
            print "Checking out %r from fedora-cvs" % (arg, )
            notify_state('fedora-vcs', { 'module': arg })
            check_call_verbose(['fedora-cvs', arg], stdout=sys.stdout, stderr=sys.stderr)
        release_dir = os.path.join(arg, release)
        for filename in os.listdir(release_dir):
            fpath = os.path.join(release_dir, filename)
            if filename.endswith('.src.rpm'):
                print "Deleting old srpm: " + fpath
                os.unlink(fpath)
    
        mock_resultdir = os.path.join('_build', arg)
        try:
            os.makedirs(mock_resultdir)
        except OSError, e:
            # assume EEXIST,
            for filename in os.listdir(mock_resultdir):
                if filename == 'lastbuild-status':
                    continue
                os.unlink(os.path.join(mock_resultdir, filename))
                
        lastbuild_filepath = os.path.join(mock_resultdir, 'lastbuild-status')
        if os.path.exists(lastbuild_filepath):
            last_build_succeeded = open(lastbuild_filepath).read() == 'success'
        else:
            last_build_succeeded = False
                
        print "Running fedpkg-vcs"
        notify_state('upstream-vcs', { 'module': arg })
        args = ['fedpkg-vcs', 'pull-update', '--status-file=' + os.path.abspath('pull-status')]
        if force or not last_build_succeeded:
            args.append('--force')
        try:
            check_call_verbose(args, stdout=sys.stdout, stderr=sys.stderr, cwd=release_dir)
        except subprocess.CalledProcessError, e:
            print "Failed: " + unicode(e)
            failed.append(arg)
            continue
            
        f = open('pull-status')
        was_updated = f.readline() == 'updated'
        f.close()

        if not was_updated and last_build_succeeded:
            print "No updates and have a previous successful build, nothing to do"
            continue

        check_call_verbose(['make', 'srpm'], stdout=sys.stdout, stderr=sys.stderr, cwd=release_dir)
        srpm = None
        for filename in os.listdir(release_dir):
            fpath = os.path.join(release_dir, filename)
            if filename.endswith('.src.rpm'):
                srpm = fpath
        if not srpm:
            print "Error: Couldn't find .src.rpm!"
            sys.exit(1)

        current_failed = False
        for mockrelease in mockreleases:
            try:
                notify_state('build', { 'module': arg, 'srpm': os.path.basename(srpm), 'target': mockrelease })
                check_call_verbose(['mock', '--configdir=_build', '-r', mockrelease, '--resultdir=' + mock_resultdir, 'rebuild', srpm], stdout=sys.stdout, stderr=sys.stderr)
            except subprocess.CalledProcessError, e:
                print "Failed: " + unicode(e)
                current_failed = True
                failed.append(arg)
                break
        if current_failed:
            f = open(lastbuild_filepath, 'w')
            f.write('failed')
            f.close()
            break
    
        print "Successfully built %r" % (arg, )    
        print "Updating repository in %r" % (resultdir, )
        linkname = os.path.join(resultdir, os.path.basename(srpm))
        if not os.path.exists(linkname):
            os.link(srpm, linkname)
        for filename in os.listdir(mock_resultdir):
            if not filename.endswith('.rpm'):
                continue
            src = os.path.join(mock_resultdir, filename)
            linkname = os.path.join(resultdir, filename)
            if os.path.exists(linkname):
                continue
            os.link(src, linkname)
        notify_state('createrepo', {})
        check_call_verbose(['createrepo', '.'], cwd=resultdir)
        if delete_old:
            proc = popen_verbose(['repomanage', '-o', '.'], stdout=subprocess.PIPE, stderr=sys.stderr, cwd=resultdir)
            output = proc.communicate()[0]
            for line in output.split('\n'):
                if line.endswith('.rpm') and os.path.exists(line):
                    os.unlink(line)
        
        f = open(lastbuild_filepath, 'w')
        f.write('success')
        f.close()
            
    if len(failed) > 0:
        sys.exit(1)
    else:
        sys.exit(0)

if __name__ == '__main__':
    main()