summaryrefslogtreecommitdiff
path: root/packages/brpm
blob: 5d16eb7149e49228279023b12e1eee2284327689 (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
229
230
231
232
#!/usr/bin/env python

import argparse
import glob
import os
import shutil
import sys
import tempfile
import time


def find_root():
    # expected path is in <top_dir>/packages/
    top_dir = os.environ.get("CLOUD_INIT_TOP_D", None)
    if top_dir is None:
        top_dir = os.path.dirname(
            os.path.dirname(os.path.abspath(sys.argv[0])))
    if os.path.isfile(os.path.join(top_dir, 'setup.py')):
        return os.path.abspath(top_dir)
    raise OSError(("Unable to determine where your cloud-init topdir is."
                   " set CLOUD_INIT_TOP_D?"))


# Use the util functions from cloudinit
sys.path.insert(0, find_root())

from cloudinit import templater
from cloudinit import util

# Map python requirements to package names.  If a match isn't found
# here, we assume 'python-<pypi_name>'.
PACKAGE_MAP = {
    'redhat': {
        'pyserial': 'pyserial',
        'pyyaml': 'PyYAML',
    },
    'suse': {
        'pyyaml': 'python-yaml',
    }
}

# Subdirectories of the ~/rpmbuild dir
RPM_BUILD_SUBDIRS = ['BUILD', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS']


def read_dependencies():
    '''Returns the Python depedencies from requirements.txt.  This explicitly
    removes 'argparse' from the list of requirements for python >= 2.7,
    because with 2.7 argparse became part of the standard library.'''
    cmd = [util.abs_join(find_root(), 'tools', 'read-dependencies')]
    (stdout, _stderr) = util.subp(cmd)
    return [p.lower().strip() for p in stdout.splitlines()
            if p != 'argparse' or (p == 'argparse'
                                   and sys.version_info[0:2] < (2, 7))]


def translate_dependencies(deps, distro):
    '''Maps python requirements into package names.  We assume
    python-<pypi_name> for packages not listed explicitly in
    PACKAGE_MAP.'''
    return [PACKAGE_MAP[distro][req]
            if req in PACKAGE_MAP[distro] else 'python-%s' % req
            for req in deps]


def read_version():
    '''Read version information.  We parse the version itself from
    the changelog, and then ask git for the commit id and distance
    from the last tag.'''
    # Figure out the version and revno
    cmd = [util.abs_join(find_root(), 'tools', 'read-version')]
    (stdout, _stderr) = util.subp(cmd)
    version = stdout.strip()

    cmd = ['git', 'describe', '--tags']
    (stdout, _stderr) = util.subp(cmd)
    git_version = stdout.strip()

    try:
        _version, distance, revno = git_version.split('-')
    except ValueError:
        distance = None
        revno = None

    return (version, distance, revno)


def generate_spec_contents(args, tmpl_fn, top_dir, arc_fn):

    # This will get us something like ('0.7.6', None, None) for a
    # tagged commit, and something like ('0.7.6', '1026', 'gd1d5796')
    # for an untagged commited.
    version, distance, revno = read_version()

    # Tmpl params
    subs = {}
    subs['version'] = version
    subs['revno'] = revno
    subs['distance'] = distance

    if distance is not None:
        now = time.strftime('%Y%m%d', time.localtime())
        release = '.%sgit%s' % (now, revno)
    else:
        release = ''

    if args.sub_release is not None:
        subs['subrelease'] = release + "." + str(args.sub_release)
    else:
        subs['subrelease'] = release

    subs['archive_name'] = arc_fn
    subs['source_name'] = os.path.basename(arc_fn).replace('.tar.gz', '')

    # Map to known packages
    python_deps = read_dependencies()
    package_deps = translate_dependencies(python_deps, args.distro)
    subs['requires'] = package_deps

    if args.boot == 'sysvinit':
        subs['sysvinit'] = True
    else:
        subs['sysvinit'] = False

    if args.boot == 'systemd':
        subs['systemd'] = True
    else:
        subs['systemd'] = False

    subs['init_sys'] = args.boot
    subs['patches'] = [os.path.basename(p) for p in args.patches]
    return templater.render_from_file(tmpl_fn, params=subs)


def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--distro", dest="distro",
                        help="select distro (default: %(default)s)",
                        metavar="DISTRO", default='redhat',
                        choices=('redhat', 'suse'))
    parser.add_argument('--srpm',
                        help='Produce a source rpm',
                        action='store_true')
    parser.add_argument("-b", "--boot", dest="boot",
                        help="select boot type (default: %(default)s)",
                        metavar="TYPE", default='sysvinit',
                        choices=('sysvinit', 'systemd'))
    parser.add_argument("-v", "--verbose", dest="verbose",
                        help=("run verbosely"
                              " (default: %(default)s)"),
                        default=False,
                        action='store_true')
    parser.add_argument('-s', "--sub-release", dest="sub_release",
                        metavar="RELEASE",
                        help=("a 'internal' release number to concat"
                              " with the bzr version number to form"
                              " the final version number"),
                        type=int,
                        default=None)
    parser.add_argument("-p", "--patch", dest="patches",
                        help=("include the following patch when building"),
                        default=[],
                        action='append')
    args = parser.parse_args()
    capture = True
    if args.verbose:
        capture = False

    workdir = None
    try:
        workdir = tempfile.mkdtemp(prefix='rpmbuild')
        os.environ['HOME'] = workdir
        topdir = os.path.join(workdir, 'rpmbuild')
        build_dirs = [os.path.join(topdir, dir)
                      for dir in RPM_BUILD_SUBDIRS]
        util.ensure_dirs(build_dirs)

        # Archive the code
        cmd = [util.abs_join(find_root(), 'tools', 'make-tarball')]
        (stdout, _stderr) = util.subp(cmd)
        archive_fn = stdout.strip()
        print "Archived source as %s" % archive_fn
        real_archive_fn = os.path.join(topdir, 'SOURCES',
                                       os.path.basename(archive_fn))
        shutil.move(archive_fn, real_archive_fn)
        print("Archived the code in %r" % (real_archive_fn))

        # Form the spec file to be used
        tmpl_fn = util.abs_join(find_root(), 'packages',
                                args.distro, 'cloud-init.spec.in')
        contents = generate_spec_contents(args, tmpl_fn, topdir,
                                          os.path.basename(archive_fn))
        spec_fn = util.abs_join(topdir, 'SPECS', 'cloud-init.spec')
        util.write_file(spec_fn, contents)
        print("Created spec file at %r" % (spec_fn))
        for p in args.patches:
            util.copy(p, util.abs_join(topdir, 'SOURCES', os.path.basename(p)))

        # Now build it!
        print("Running 'rpmbuild' in %r" % (topdir))

        if args.srpm:
            cmd = ['rpmbuild', '-bs', '--nodeps', spec_fn]
        else:
            cmd = ['rpmbuild', '-ba', spec_fn]

        util.subp(cmd, capture=capture)

        # Copy the items built to our local dir
        globs = []
        globs.extend(glob.glob("%s/*.rpm" %
                               (util.abs_join(topdir, 'RPMS', 'noarch'))))
        globs.extend(glob.glob("%s/*.rpm" %
                               (util.abs_join(topdir, 'RPMS', 'x86_64'))))
        globs.extend(glob.glob("%s/*.rpm" %
                               (util.abs_join(topdir, 'RPMS'))))
        globs.extend(glob.glob("%s/*.rpm" %
                               (util.abs_join(topdir, 'SRPMS'))))
        for rpm_fn in globs:
            tgt_fn = util.abs_join(os.getcwd(), os.path.basename(rpm_fn))
            shutil.move(rpm_fn, tgt_fn)
            print("Wrote out %s package %r" % (args.distro, tgt_fn))
    finally:
        if workdir is not None:
            shutil.rmtree(workdir)

    return 0


if __name__ == '__main__':
    sys.exit(main())