[r60]: / trunk / wharfie / wharfie.py  Maximize  Restore  History

Download this file

293 lines (258 with data), 11.5 kB

  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
#!/usr/bin/python
#
# Copyright 2017 Ingo Hornberger <ingo_@gmx.net>
#
# This software is licensed under the MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be included in all copies
# or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
################################################################################
#
# The file format and the principle are lent from Docker.
# It's just all a bit simpler, as we only create images
# and have no infrastructure to provide prebuilt images.
#
# What is more complex for embedded systems is the legal
# part. When s.o. is using docker to build a web service,
# he doesn't include the used open source software into
# a product, which he is commercially using, but he uses
# it himself to provide a web service to his customers.
#
# With most embedded systems, which Wharfie is focusing
# on, this is different. People are usually building
# products, including the open source software. So they
# need to respect the licenses of the software, which
# they are including.
#
# For this reason Wharfie only supports debian based
# systems, as the debian projects takes much care about
# respecting open source licenses, and makes it easy
# to get a list of all licenses used in a system.
#
# It makes it also easy to get the source packets, fitting
# to the installed binary version. Therefore, one can
# easily provide all sources of the open source software,
# included in his image to his customers.
#
# With this background, the supported commands of Wharfie
# are differing slightly from its big brother Docker.
#
# Commands:
# - FROM: Supports only a fix number of build rules.
#         e.g.: debian_armhf_sid, debian_etch, ...
#
# - RUN: Execute a command inside the image
#
# - RUN HOST: Execute a command on the host system,
#             But inside of the image root.
#
# - ADD: Add an archive or file to the root filesystem.
#
# - TO: name of the final archive
#
# - SOURCE: name of an archive, where the currently installed
#           source packages are written to.
#
# - LICENSE: Extract a list of all licenses, of all currently
#            installed packages.
#
# - TOOLCHAIN: Build a cross-toolchain for the currently
#              installed root filesystem.
#
# Note: Technically everything can be done, using RUN
#       and RUN HOST. Other commands, like ADD or TO
#       are only supported for more convenience.
#       So for example if you want to combine the
#       resulting image with a special bootloader or
#       something, it can be flexibly done with RUN HOST.


import os
import re
import sys
import glob
import binascii
import argparse
from shutil import copyfile
from lib import makefile as make
from lib import actions
from lib import files

regexCommand = '^[ \t]*(RUN HOST|RUN|FROM|TOOLCHAIN|TO|ADD|COPY|WORKDIR|ENTRYPOINT|SOURCE|LICENSE|ENV|ARG|EXPOSE|[a-zA-Z0-9]+)([^\n]*)';
g_depend = '';

#
# Read a Wharfile
#
def read_wharfile(filename):
    content = open(filename, 'r').read()
    content = content.replace('\\\n', '')
    bld = ''
    g_allDepends = '';
    g_depend = '';
    for cmd in re.findall(regexCommand, content, flags=re.MULTILINE):
        # calculate current build target and dependency names
        dep = list();
        if bld != '':
            dep.append(bld);
        if g_depend != '':
            dep.append(g_depend);

        if cmd[0] not in ('FROM', 'ENV', 'ARG', 'EXPOSE', 'WORKDIR'):
            g_allDepends += str(cmd);
            if g_allDepends != '':
                bld = format(0xFFFFFFFF & binascii.crc32(g_allDepends), '02X') + ".piling.tar";

        # EXPOSE
        if cmd[0] == 'EXPOSE':
            pass
        # WORKDIR
        elif cmd[0] == 'WORKDIR':
            actions.workingdir(bld, dep, cmd)
        # FROM
        elif cmd[0] == 'FROM':
            # special handling for debootstrap
            if cmd[1].lstrip().startswith("debian_"):
                g_depend = cmd[1].lstrip() + ".tar";
            else:
                g_depend = files.input_file(cmd[1]);

        # ENV / ARG
        elif cmd[0] == 'ENV' or cmd[0] == 'ARG':
            arg = cmd[1].lstrip()
            if (not " " in arg) and ("=" in arg):
                arg = arg.replace("=", " ")
            make.environment.append(arg);

        # RUN
        elif cmd[0] == 'RUN':
            makeTarget=actions.run(bld, dep, cmd)
            make.makeTargets.append(makeTarget);
            g_depend = '';

        # RUN HOST
        elif cmd[0] == 'RUN HOST':
            makeTarget=actions.run_host(bld, dep, cmd)
            make.makeTargets.append(makeTarget);
            g_depend = '';

        # ENTRYPOINT
        elif cmd[0] == 'ENTRYPOINT':
            makeTarget=actions.entrypoint(bld, dep, cmd)
            make.makeTargets.append(makeTarget);
            g_depend = '';

        # COPY (same as add, but w/o magic)
        elif cmd[0] == 'COPY':
            makeTarget=actions.copy(bld, dep, cmd)
            make.makeTargets.append(makeTarget);
            g_depend = '';

        # ADD
        elif cmd[0] == 'ADD':
            makeTarget=actions.add(bld, dep, cmd)
            make.makeTargets.append(makeTarget);
            g_depend = '';

        # TO
        elif cmd[0] == 'TO':
            makeTarget=actions.to(bld, dep, cmd)
            bld = makeTarget["name"]
            make.makeTargets.append(makeTarget);
            g_depend = '';

        # SOURCE
        elif cmd[0] == 'SOURCE':
            makeTarget=actions.source(bld, dep, cmd)
            make.makeTargets.append(makeTarget);
            g_depend = '';

        # LICENSE
        elif cmd[0] == 'LICENSE':
            makeTarget=actions.license(bld, dep, cmd)
            make.makeTargets.append(makeTarget);
            g_depend = '';

        # TOOLCHAIN
        elif cmd[0] == 'TOOLCHAIN':
            makeTarget=actions.toolchain(bld, dep, cmd)
            make.makeTargets.append(makeTarget);
            g_depend = '';

        else:
            print ('error: parse error in Wharfile');
            print ('error: unknown command: "%s %s"' % (cmd[0], cmd[1]));
            exit(-1);

    make.finalTarget.append(bld);


        
#
# Main
#
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--clean', action='store_true', help="Clear intermediate files" )
    parser.add_argument('--info', action='store_true', help="Print info about already generated image" )
    parser.add_argument('--incremental', action='store_true', help="An experimental feature, which uses incremental backup mechanisms of tar." )
    parser.add_argument('--gen-only', action='store_true', help="Generate makefile only, but don't build it" )
    parser.add_argument('--dry-run', action='store_true', help="Generate makefile with disabled run actions and don't build it" )
    parser.add_argument('--qemu', action='store_true', help="Enable qemu build (default if qemu support is available)" )
    parser.add_argument('--no-qemu', action='store_true', help="Even if qemu support for wharfie is available, run without" )
    parser.add_argument('--no-proc', action='store_true', help="suppress mounting of the proc filesystem." )
    parser.add_argument('--verbose', action='store_true', help="Print verbose make output" )
    parser.add_argument('wharfile', default='Wharfile', nargs='?', help="Filename of a 'Wharfile'. By default ./Wharfile is used." )
    args = parser.parse_args()

    # check if qemu should be used
    if os.path.isfile(os.path.abspath(os.path.dirname(sys.argv[0])) + "/qemu/qwharfie.qcow"):
        args.qemu = True
    else:
        if args.qemu:
            print("error: qemu build forced, but no qemu support available.")
            exit(1)
            
    if args.no_qemu:
        args.qemu = False

    # If qemu is used, we generate only the make file. The build is then done in a second stage.
    if args.qemu:
        args.gen_only=True
    
    # generate makefile
    if os.path.isfile(args.wharfile):
        read_wharfile(args.wharfile);
    else:
        print("error: Wharfile '%s' not found." % args.wharfile)
        exit(1)

    if os.path.isfile(os.path.abspath(os.path.dirname(sys.argv[0])) + "/wharfie.mk"):
        make.write_makefile('Makefile', args.dry_run, os.path.dirname(sys.argv[0]), args.incremental, not args.no_proc);
    else:
        make.write_makefile('Makefile', args.dry_run, os.path.abspath(os.path.dirname(sys.argv[0])) + "/../share/wharfie", args.incremental, not args.no_proc);

    # call make
    flags=""
    if args.verbose:
        flags+=" VERBOSE=y"
    
    if args.clean:
        os.system("make %s clean" % flags)
    elif args.info:
        os.system("make %s info" % flags)
    elif not args.gen_only and not args.dry_run:
        os.system("make %s" % flags);

    # call qemu if enabled
    if args.qemu and not args.clean:
        qemu = "qemu-system-x86_64"
        disk = os.path.dirname(sys.argv[0]) + "/qemu/qwharfie.qcow"
        cache = "qwharfie.cache.qcow"
        input = "qwharfie.input.raw"
        output = "qwharfie.output.raw"
        kernel = glob.glob(os.path.dirname(sys.argv[0]) + "/qemu/boot/vmlinuz*")[0]
        initrd = glob.glob(os.path.dirname(sys.argv[0]) + "/qemu/boot/initrd*")[0]
        
        uuid = open(os.path.dirname(sys.argv[0]) + "/qemu/qwharfie.qcow.uuid", "r").readline().rstrip()

        # copy cache and output
        if not os.path.isfile(cache):
            copyfile(os.path.dirname(sys.argv[0]) + "/qemu/" + cache, cache)
        copyfile(os.path.dirname(sys.argv[0]) + "/qemu/" + output, output)
        copyfile(os.path.dirname(sys.argv[0]) + "/wharfie.mk", "wharfie.mk")

        input_command='tar --exclude="%s" --exclude="%s" --exclude="%s" -cf %s .' % (input, output, cache, input)
        qemu_command='%s -machine accel=kvm -m 512 -drive file=%s,index=0,media=disk,snapshot=on -drive file=%s,index=1,media=disk,snapshot=off -drive file=%s,index=2,media=disk,snapshot=off -drive file=%s,index=3,media=disk,snapshot=off -net nic,model=virtio -net user -kernel %s -initrd %s -append "root=UUID=%s ro single console=ttyS0 fsck.mode=skip systemd.unit=multi-user.target" -nographic' % (qemu, disk, cache, input, output, kernel, initrd, uuid)
        output_command='tar -xf %s' % (output)
        print("cmd: %s\n" % input_command)
        os.system(input_command);
        print("cmd: %s\n" % qemu_command)
        os.system(qemu_command);
        print("cmd: %s\n" % output_command)
        os.system(output_command);
        
        
if __name__ == "__main__":
    main()