aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/wic
blob: 25b0d676fdb4de52a6d637a181f82bf4f00c53b0 (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
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
#!/usr/bin/env python
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (c) 2013, Intel Corporation.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# DESCRIPTION 'wic' is the OpenEmbedded Image Creator that users can
# use to generate bootable images.  Invoking it without any arguments
# will display help screens for the 'wic' command and list the
# available 'wic' subcommands.  Invoking a subcommand without any
# arguments will likewise display help screens for the specified
# subcommand.  Please use that interface for detailed help.
#
# AUTHORS
# Tom Zanussi <tom.zanussi (at] linux.intel.com>
#

__version__ = "0.2.0"

# Python Standard Library modules
import os
import sys
import optparse
import logging
from distutils import spawn

# External modules
scripts_path = os.path.abspath(os.path.dirname(__file__))
lib_path = scripts_path + '/lib'
sys.path.append(lib_path)

bitbake_exe = spawn.find_executable('bitbake')
if bitbake_exe:
    bitbake_path = os.path.join(os.path.dirname(bitbake_exe), '../lib')
    sys.path.append(bitbake_path)
    from bb import cookerdata
    from bb.main import bitbake_main, BitBakeConfigParameters
else:
    bitbake_main = None

from wic.utils.oe.misc import get_bitbake_var, BB_VARS
from wic.utils.errors import WicError
from image import engine
from image import help as hlp

def rootfs_dir_to_args(krootfs_dir):
    """
    Get a rootfs_dir dict and serialize to string
    """
    rootfs_dir = ''
    for k, v in krootfs_dir.items():
        rootfs_dir += ' '
        rootfs_dir += '='.join([k, v])
    return rootfs_dir.strip()

def callback_rootfs_dir(option, opt, value, parser):
    """
    Build a dict using --rootfs_dir connection=dir
    """
    if not type(parser.values.rootfs_dir) is dict:
        parser.values.rootfs_dir = dict()

    if '=' in value:
        (key, rootfs_dir) = value.split('=')
    else:
        key = 'ROOTFS_DIR'
        rootfs_dir = value

    parser.values.rootfs_dir[key] = rootfs_dir

def wic_create_subcommand(args, usage_str):
    """
    Command-line handling for image creation.  The real work is done
    by image.engine.wic_create()
    """
    parser = optparse.OptionParser(usage=usage_str)

    parser.add_option("-o", "--outdir", dest="outdir",
                      help="name of directory to create image in")
    parser.add_option("-e", "--image-name", dest="image_name",
                      help="name of the image to use the artifacts from "
                           "e.g. core-image-sato")
    parser.add_option("-r", "--rootfs-dir", dest="rootfs_dir", type="string",
                      action="callback", callback=callback_rootfs_dir,
                      help="path to the /rootfs dir to use as the "
                           ".wks rootfs source")
    parser.add_option("-b", "--bootimg-dir", dest="bootimg_dir",
                      help="path to the dir containing the boot artifacts "
                           "(e.g. /EFI or /syslinux dirs) to use as the "
                           ".wks bootimg source")
    parser.add_option("-k", "--kernel-dir", dest="kernel_dir",
                      help="path to the dir containing the kernel to use "
                           "in the .wks bootimg")
    parser.add_option("-n", "--native-sysroot", dest="native_sysroot",
                      help="path to the native sysroot containing the tools "
                           "to use to build the image")
    parser.add_option("-p", "--skip-build-check", dest="build_check",
                      action="store_false", default=True, help="skip the build check")
    parser.add_option("-f", "--build-rootfs", action="store_true", help="build rootfs")
    parser.add_option("-c", "--compress-with", choices=("gzip", "bzip2", "xz"),
                      dest='compressor',
                      help="compress image with specified compressor")
    parser.add_option("-v", "--vars", dest='vars_dir',
                      help="directory with <image>.env files that store "
                           "bitbake variables")
    parser.add_option("-D", "--debug", dest="debug", action="store_true",
                      default=False, help="output debug information")

    (options, args) = parser.parse_args(args)

    if len(args) != 1:
        logging.error("Wrong number of arguments, exiting\n")
        parser.print_help()
        sys.exit(1)

    if options.build_rootfs and not bitbake_main:
        logging.error("Can't build roofs as bitbake is not in the $PATH")
        sys.exit(1)

    if not options.image_name:
        missed = []
        for val, opt in [(options.rootfs_dir, 'rootfs-dir'),
                         (options.bootimg_dir, 'bootimg-dir'),
                         (options.kernel_dir, 'kernel-dir'),
                         (options.native_sysroot, 'native-sysroot')]:
            if not val:
                missed.append(opt)
        if missed:
            print "The following build artifacts are not specified:"
            print "  " + ", ".join(missed)
            sys.exit(1)

    if options.image_name:
        BB_VARS.default_image = options.image_name
    else:
        options.build_check = False

    if options.vars_dir:
        BB_VARS.vars_dir = options.vars_dir

    if options.build_check:
        print "Checking basic build environment..."
        if not engine.verify_build_env():
            print "Couldn't verify build environment, exiting\n"
            sys.exit(1)
        else:
            print "Done.\n"

    bootimg_dir = ""

    if options.image_name:
        if options.build_rootfs:
            argv = ["bitbake", options.image_name]
            if options.debug:
                argv.append("--debug")

            print "Building rootfs...\n"
            if bitbake_main(BitBakeConfigParameters(argv),
                            cookerdata.CookerConfiguration()):
                sys.exit(1)

        rootfs_dir = get_bitbake_var("IMAGE_ROOTFS", options.image_name)
        kernel_dir = get_bitbake_var("DEPLOY_DIR_IMAGE", options.image_name)
        native_sysroot = get_bitbake_var("STAGING_DIR_NATIVE",
                                         options.image_name)
    else:
        if options.build_rootfs:
            print "Image name is not specified, exiting. (Use -e/--image-name to specify it)\n"
            sys.exit(1)

    wks_file = args[0]

    if not wks_file.endswith(".wks"):
        wks_file = engine.find_canned_image(scripts_path, wks_file)
        if not wks_file:
            print "No image named %s found, exiting.  (Use 'wic list images' "\
                  "to list available images, or specify a fully-qualified OE "\
                  "kickstart (.wks) filename)\n" % args[0]
            sys.exit(1)

    image_output_dir = ""
    if options.outdir:
        image_output_dir = options.outdir

    if not options.image_name:
        rootfs_dir = ''
        if 'ROOTFS_DIR' in options.rootfs_dir:
            rootfs_dir = options.rootfs_dir['ROOTFS_DIR']
        bootimg_dir = options.bootimg_dir
        kernel_dir = options.kernel_dir
        native_sysroot = options.native_sysroot
        if rootfs_dir and not os.path.isdir(rootfs_dir):
            print "--roofs-dir (-r) not found, exiting\n"
            sys.exit(1)
        if not os.path.isdir(bootimg_dir):
            print "--bootimg-dir (-b) not found, exiting\n"
            sys.exit(1)
        if not os.path.isdir(kernel_dir):
            print "--kernel-dir (-k) not found, exiting\n"
            sys.exit(1)
        if not os.path.isdir(native_sysroot):
            print "--native-sysroot (-n) not found, exiting\n"
            sys.exit(1)
    else:
        not_found = not_found_dir = ""
        if not os.path.isdir(rootfs_dir):
            (not_found, not_found_dir) = ("rootfs-dir", rootfs_dir)
        elif not os.path.isdir(kernel_dir):
            (not_found, not_found_dir) = ("kernel-dir", kernel_dir)
        elif not os.path.isdir(native_sysroot):
            (not_found, not_found_dir) = ("native-sysroot", native_sysroot)
        if not_found:
            if not not_found_dir:
                not_found_dir = "Completely missing artifact - wrong image (.wks) used?"
            print "Build artifacts not found, exiting."
            print "  (Please check that the build artifacts for the machine"
            print "   selected in local.conf actually exist and that they"
            print "   are the correct artifacts for the image (.wks file)).\n"
            print "The artifact that couldn't be found was %s:\n  %s" % \
                (not_found, not_found_dir)
            sys.exit(1)

    krootfs_dir = options.rootfs_dir
    if krootfs_dir is None:
        krootfs_dir = {}
        krootfs_dir['ROOTFS_DIR'] = rootfs_dir

    rootfs_dir = rootfs_dir_to_args(krootfs_dir)

    print "Creating image(s)...\n"
    engine.wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
                      native_sysroot, scripts_path, image_output_dir,
                      options.compressor, options.debug)


def wic_list_subcommand(args, usage_str):
    """
    Command-line handling for listing available image properties and
    values.  The real work is done by image.engine.wic_list()
    """
    parser = optparse.OptionParser(usage=usage_str)

    parser.add_option("-o", "--outfile", action="store",
                      dest="properties_file",
                      help="dump the possible values for image properties to a JSON file")

    (options, args) = parser.parse_args(args)

    if not engine.wic_list(args, scripts_path, options.properties_file):
        logging.error("Bad list arguments, exiting\n")
        parser.print_help()
        sys.exit(1)


def wic_help_topic_subcommand(args, usage_str):
    """
    Command-line handling for help-only 'subcommands'.  This is
    essentially a dummy command that doesn nothing but allow users to
    use the existing subcommand infrastructure to display help on a
    particular topic not attached to any particular subcommand.
    """
    pass


wic_help_topic_usage = """
"""

subcommands = {
    "create":    [wic_create_subcommand,
                  hlp.wic_create_usage,
                  hlp.wic_create_help],
    "list":      [wic_list_subcommand,
                  hlp.wic_list_usage,
                  hlp.wic_list_help],
    "plugins":   [wic_help_topic_subcommand,
                  wic_help_topic_usage,
                  hlp.get_wic_plugins_help],
    "overview":  [wic_help_topic_subcommand,
                  wic_help_topic_usage,
                  hlp.wic_overview_help],
    "kickstart": [wic_help_topic_subcommand,
                  wic_help_topic_usage,
                  hlp.wic_kickstart_help],
}


def start_logging(loglevel):
    logging.basicConfig(filname='wic.log', filemode='w', level=loglevel)


def main(argv):
    parser = optparse.OptionParser(version="wic version %s" % __version__,
                                   usage=hlp.wic_usage)

    parser.disable_interspersed_args()

    (options, args) = parser.parse_args(argv)

    if len(args):
        if args[0] == "help":
            if len(args) == 1:
                parser.print_help()
                sys.exit(1)

    return hlp.invoke_subcommand(args, parser, hlp.wic_help_usage, subcommands)


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except WicError as err:
        print >> sys.stderr, "ERROR:", err
        sys.exit(1)
ol upgrade</filename> to Create a Version of the Recipe that Supports a Newer Version of the Software</ulink>" section in the Yocto Project Application Development and the Extensible Software Development Kit (eSDK) manual. You can also see an example of how to use <filename>devtool upgrade</filename> in the "<ulink url='&YOCTO_DOCS_DEV_URL;#gs-using-devtool-upgrade'>Using <filename>devtool upgrade</filename></ulink>" section in the Yocto Project Development Tasks Manual. </para> </section> <section id='devtool-resetting-a-recipe'> <title>Resetting a Recipe</title> <para> Use the <filename>devtool reset</filename> command to remove a recipe and its configuration (e.g. the corresponding <filename>.bbappend</filename> file) from the workspace layer. Realize that this command deletes the recipe and the append file. The command does not physically move them for you. Consequently, you must be sure to physically relocate your updated recipe and the append file outside of the workspace layer before running the <filename>devtool reset</filename> command. </para> <para> If the <filename>devtool reset</filename> command detects that the recipe or the append files have been modified, the command preserves the modified files in a separate "attic" subdirectory under the workspace layer. </para> <para> Here is an example that resets the workspace directory that contains the <filename>mtr</filename> recipe: <literallayout class='monospaced'> $ devtool reset mtr NOTE: Cleaning sysroot for recipe mtr... NOTE: Leaving source tree /home/scottrif/poky/build/workspace/sources/mtr as-is; if you no longer need it then please delete it manually $ </literallayout> </para> </section> <section id='devtool-building-your-recipe'> <title>Building Your Recipe</title> <para> Use the <filename>devtool build</filename> command to cause the OpenEmbedded build system to build your recipe. The <filename>devtool build</filename> command is equivalent to <filename>bitbake -c populate_sysroot</filename>. </para> <para> When you use the <filename>devtool build</filename> command, you must supply the root name of the recipe (i.e. no version, paths, or extensions). You can use either the "-s" or the "--disable-parallel-make" option to disable parallel makes during the build. Here is an example: <literallayout class='monospaced'> $ devtool build <replaceable>recipe</replaceable> </literallayout> </para> </section> <section id='devtool-building-your-image'> <title>Building Your Image</title> <para> Use the <filename>devtool build-image</filename> command to build an image, extending it to include packages from recipes in the workspace. Using this command is useful when you want an image that ready for immediate deployment onto a device for testing. For proper integration into a final image, you need to edit your custom image recipe appropriately. </para> <para> When you use the <filename>devtool build-image</filename> command, you must supply the name of the image. This command has no command line options: <literallayout class='monospaced'> $ devtool build-image <replaceable>image</replaceable> </literallayout> </para> </section> <section id='devtool-deploying-your-software-on-the-target-machine'> <title>Deploying Your Software on the Target Machine</title> <para> Use the <filename>devtool deploy-target</filename> command to deploy the recipe's build output to the live target machine: <literallayout class='monospaced'> $ devtool deploy-target <replaceable>recipe</replaceable>&nbsp;<replaceable>target</replaceable> </literallayout> The <replaceable>target</replaceable> is the address of the target machine, which must be running an SSH server (i.e. <filename>user@hostname[:destdir]</filename>). </para> <para> This command deploys all files installed during the <link linkend='ref-tasks-install'><filename>do_install</filename></link> task. Furthermore, you do not need to have package management enabled within the target machine. If you do, the package manager is bypassed. <note><title>Notes</title> <para> The <filename>deploy-target</filename> functionality is for development only. You should never use it to update an image that will be used in production. </para> </note> </para> <para> Some conditions exist that could prevent a deployed application from behaving as expected. When both of the following conditions exist, your application has the potential to not behave correctly when run on the target: <itemizedlist> <listitem><para> You are deploying a new application to the target and the recipe you used to build the application had correctly defined runtime dependencies. </para></listitem> <listitem><para> The target does not physically have the packages on which the application depends installed. </para></listitem> </itemizedlist> If both of these conditions exist, your application will not behave as expected. The reason for this misbehavior is because the <filename>devtool deploy-target</filename> command does not deploy the packages (e.g. libraries) on which your new application depends. The assumption is that the packages are already on the target. Consequently, when a runtime call is made in the application for a dependent function (e.g. a library call), the function cannot be found. </para> <para> To be sure you have all the dependencies local to the target, you need to be sure that the packages are pre-deployed (installed) on the target before attempting to run your application. </para> </section> <section id='devtool-removing-your-software-from-the-target-machine'> <title>Removing Your Software from the Target Machine</title> <para> Use the <filename>devtool undeploy-target</filename> command to remove deployed build output from the target machine. For the <filename>devtool undeploy-target</filename> command to work, you must have previously used the <link linkend='devtool-deploying-your-software-on-the-target-machine'><filename>devtool deploy-target</filename></link> command. <literallayout class='monospaced'> $ devtool undeploy-target <replaceable>recipe</replaceable>&nbsp;<replaceable>target</replaceable> </literallayout> The <replaceable>target</replaceable> is the address of the target machine, which must be running an SSH server (i.e. <filename>user@hostname</filename>). </para> </section> <section id='devtool-creating-the-workspace'> <title>Creating the Workspace Layer in an Alternative Location</title> <para> Use the <filename>devtool create-workspace</filename> command to create a new workspace layer in your <link linkend='build-directory'>Build Directory</link>. When you create a new workspace layer, it is populated with the <filename>README</filename> file and the <filename>conf</filename> directory only. </para> <para> The following example creates a new workspace layer in your current working and by default names the workspace layer "workspace": <literallayout class='monospaced'> $ devtool create-workspace </literallayout> </para> <para> You can create a workspace layer anywhere by supplying a pathname with the command. The following command creates a new workspace layer named "new-workspace": <literallayout class='monospaced'> $ devtool create-workspace /home/scottrif/new-workspace </literallayout> </para> </section> <section id='devtool-get-the-status-of-the-recipes-in-your-workspace'> <title>Get the Status of the Recipes in Your Workspace</title> <para> Use the <filename>devtool status</filename> command to list the recipes currently in your workspace. Information includes the paths to their respective external source trees. </para> <para> The <filename>devtool status</filename> command has no command-line options: <literallayout class='monospaced'> $ devtool status </literallayout> Following is sample output after using <link linkend='devtool-adding-a-new-recipe-to-the-workspace'><filename>devtool add</filename></link> to create and add the <filename>mtr_0.86.bb</filename> recipe to the <filename>workspace</filename> directory: <literallayout class='monospaced'> $ devtool status mtr: /home/scottrif/poky/build/workspace/sources/mtr (/home/scottrif/poky/build/workspace/recipes/mtr/mtr_0.86.bb) $ </literallayout> </para> </section> <section id='devtool-search-for-available-target-recipes'> <title>Search for Available Target Recipes</title> <para> Use the <filename>devtool search</filename> command to search for available target recipes. The command matches the recipe name, package name, description, and installed files. The command displays the recipe name as a result of a match. </para> <para> When you use the <filename>devtool search</filename> command, you must supply a <replaceable>keyword</replaceable>. The command uses the <replaceable>keyword</replaceable> when searching for a match. </para> </section> </chapter> <!-- vim: expandtab tw=80 ts=4 -->