xref: /OK3568_Linux_fs/yocto/poky/meta/classes/update-alternatives.bbclass (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1# This class is used to help the alternatives system which is useful when
2# multiple sources provide the same command. You can use update-alternatives
3# command directly in your recipe, but in most cases this class simplifies
4# that job.
5#
6# To use this class a number of variables should be defined:
7#
8# List all of the alternatives needed by a package:
9# ALTERNATIVE:<pkg> = "name1 name2 name3 ..."
10#
11#   i.e. ALTERNATIVE:busybox = "sh sed test bracket"
12#
13# The pathname of the link
14# ALTERNATIVE_LINK_NAME[name] = "target"
15#
16#   This is the name of the binary once it's been installed onto the runtime.
17#   This name is global to all split packages in this recipe, and should match
18#   other recipes with the same functionality.
19#   i.e. ALTERNATIVE_LINK_NAME[bracket] = "/usr/bin/["
20#
21# NOTE: If ALTERNATIVE_LINK_NAME is not defined, it defaults to ${bindir}/name
22#
23# The default link to create for all targets
24# ALTERNATIVE_TARGET = "target"
25#
26#   This is useful in a multicall binary case
27#   i.e. ALTERNATIVE_TARGET = "/bin/busybox"
28#
29# A non-default link to create for a target
30# ALTERNATIVE_TARGET[name] = "target"
31#
32#   This is the name of the binary as it's been installed by do_install
33#   i.e. ALTERNATIVE_TARGET[sh] = "/bin/bash"
34#
35# A package specific link for a target
36# ALTERNATIVE_TARGET_<pkg>[name] = "target"
37#
38#   This is useful when a recipe provides multiple alternatives for the
39#   same item.
40#
41# NOTE: If ALTERNATIVE_TARGET is not defined, it will inherit the value
42# from ALTERNATIVE_LINK_NAME.
43#
44# NOTE: If the ALTERNATIVE_LINK_NAME and ALTERNATIVE_TARGET are the same,
45# ALTERNATIVE_TARGET will have '.{BPN}' appended to it.  If the file
46# referenced has not been renamed, it will also be renamed.  (This avoids
47# the need to rename alternative files in the do_install step, but still
48# supports it if necessary for some reason.)
49#
50# The default priority for any alternatives
51# ALTERNATIVE_PRIORITY = "priority"
52#
53#   i.e. default is ALTERNATIVE_PRIORITY = "10"
54#
55# The non-default priority for a specific target
56# ALTERNATIVE_PRIORITY[name] = "priority"
57#
58# The package priority for a specific target
59# ALTERNATIVE_PRIORITY_<pkg>[name] = "priority"
60
61ALTERNATIVE_PRIORITY = "10"
62
63# We need special processing for vardeps because it can not work on
64# modified flag values.  So we aggregate the flags into a new variable
65# and include that variable in the set.
66UPDALTVARS  = "ALTERNATIVE ALTERNATIVE_LINK_NAME ALTERNATIVE_TARGET ALTERNATIVE_PRIORITY"
67
68PACKAGE_WRITE_DEPS += "virtual/update-alternatives-native"
69
70def gen_updatealternativesvardeps(d):
71    pkgs = (d.getVar("PACKAGES") or "").split()
72    vars = (d.getVar("UPDALTVARS") or "").split()
73
74    # First compute them for non_pkg versions
75    for v in vars:
76        for flag in sorted((d.getVarFlags(v) or {}).keys()):
77            if flag == "doc" or flag == "vardeps" or flag == "vardepsexp":
78                continue
79            d.appendVar('%s_VARDEPS' % (v), ' %s:%s' % (flag, d.getVarFlag(v, flag, False)))
80
81    for p in pkgs:
82        for v in vars:
83            for flag in sorted((d.getVarFlags("%s_%s" % (v,p)) or {}).keys()):
84                if flag == "doc" or flag == "vardeps" or flag == "vardepsexp":
85                    continue
86                d.appendVar('%s_VARDEPS_%s' % (v,p), ' %s:%s' % (flag, d.getVarFlag('%s_%s' % (v,p), flag, False)))
87
88def ua_extend_depends(d):
89    if not 'virtual/update-alternatives' in d.getVar('PROVIDES'):
90        d.appendVar('DEPENDS', ' virtual/${MLPREFIX}update-alternatives')
91
92def update_alternatives_enabled(d):
93    # Update Alternatives only works on target packages...
94    if bb.data.inherits_class('native', d) or \
95       bb.data.inherits_class('cross', d) or bb.data.inherits_class('crosssdk', d) or \
96       bb.data.inherits_class('cross-canadian', d):
97        return False
98
99    # Disable when targeting mingw32 (no target support)
100    if d.getVar("TARGET_OS") == "mingw32":
101        return False
102
103    return True
104
105python __anonymous() {
106    if not update_alternatives_enabled(d):
107        return
108
109    # compute special vardeps
110    gen_updatealternativesvardeps(d)
111
112    # extend the depends to include virtual/update-alternatives
113    ua_extend_depends(d)
114}
115
116def gen_updatealternativesvars(d):
117    ret = []
118    pkgs = (d.getVar("PACKAGES") or "").split()
119    vars = (d.getVar("UPDALTVARS") or "").split()
120
121    for v in vars:
122        ret.append(v + "_VARDEPS")
123
124    for p in pkgs:
125        for v in vars:
126            ret.append(v + ":" + p)
127            ret.append(v + "_VARDEPS_" + p)
128    return " ".join(ret)
129
130# Now the new stuff, we use a custom function to generate the right values
131populate_packages[vardeps] += "${UPDALTVARS} ${@gen_updatealternativesvars(d)}"
132
133# We need to do the rename after the image creation step, but before
134# the split and strip steps..  PACKAGE_PREPROCESS_FUNCS is the right
135# place for that.
136PACKAGE_PREPROCESS_FUNCS += "apply_update_alternative_renames"
137python apply_update_alternative_renames () {
138    if not update_alternatives_enabled(d):
139       return
140
141    import re
142
143    def update_files(alt_target, alt_target_rename, pkg, d):
144        f = d.getVar('FILES:' + pkg)
145        if f:
146            f = re.sub(r'(^|\s)%s(\s|$)' % re.escape (alt_target), r'\1%s\2' % alt_target_rename, f)
147            d.setVar('FILES:' + pkg, f)
148
149    # Check for deprecated usage...
150    pn = d.getVar('BPN')
151    if d.getVar('ALTERNATIVE_LINKS') != None:
152        bb.fatal('%s: Use of ALTERNATIVE_LINKS/ALTERNATIVE_PATH/ALTERNATIVE_NAME is no longer supported, please convert to the updated syntax, see update-alternatives.bbclass for more info.' % pn)
153
154    # Do actual update alternatives processing
155    pkgdest = d.getVar('PKGD')
156    for pkg in (d.getVar('PACKAGES') or "").split():
157        # If the src == dest, we know we need to rename the dest by appending ${BPN}
158        link_rename = []
159        for alt_name in (d.getVar('ALTERNATIVE:%s' % pkg) or "").split():
160            alt_link     = d.getVarFlag('ALTERNATIVE_LINK_NAME', alt_name)
161            if not alt_link:
162                alt_link = "%s/%s" % (d.getVar('bindir'), alt_name)
163                d.setVarFlag('ALTERNATIVE_LINK_NAME', alt_name, alt_link)
164            if alt_link.startswith(os.path.join(d.getVar('sysconfdir'), 'init.d')):
165                # Managing init scripts does not work (bug #10433), foremost
166                # because of a race with update-rc.d
167                bb.fatal("Using update-alternatives for managing SysV init scripts is not supported")
168
169            alt_target   = d.getVarFlag('ALTERNATIVE_TARGET_%s' % pkg, alt_name) or d.getVarFlag('ALTERNATIVE_TARGET', alt_name)
170            alt_target   = alt_target or d.getVar('ALTERNATIVE_TARGET_%s' % pkg) or d.getVar('ALTERNATIVE_TARGET') or alt_link
171            # Sometimes alt_target is specified as relative to the link name.
172            alt_target   = os.path.join(os.path.dirname(alt_link), alt_target)
173
174            # If the link and target are the same name, we need to rename the target.
175            if alt_link == alt_target:
176                src = '%s/%s' % (pkgdest, alt_target)
177                alt_target_rename = '%s.%s' % (alt_target, pn)
178                dest = '%s/%s' % (pkgdest, alt_target_rename)
179                if os.path.lexists(dest):
180                    bb.note('%s: Already renamed: %s' % (pn, alt_target_rename))
181                elif os.path.lexists(src):
182                    if os.path.islink(src):
183                        # Delay rename of links
184                        link_rename.append((alt_target, alt_target_rename))
185                    else:
186                        bb.note('%s: Rename %s -> %s' % (pn, alt_target, alt_target_rename))
187                        bb.utils.rename(src, dest)
188                        update_files(alt_target, alt_target_rename, pkg, d)
189                else:
190                    bb.warn("%s: alternative target (%s or %s) does not exist, skipping..." % (pn, alt_target, alt_target_rename))
191                    continue
192                d.setVarFlag('ALTERNATIVE_TARGET_%s' % pkg, alt_name, alt_target_rename)
193
194        # Process delayed link names
195        # Do these after other renames so we can correct broken links
196        for (alt_target, alt_target_rename) in link_rename:
197            src = '%s/%s' % (pkgdest, alt_target)
198            dest = '%s/%s' % (pkgdest, alt_target_rename)
199            link_target = oe.path.realpath(src, pkgdest, True)
200
201            if os.path.lexists(link_target):
202                # Ok, the link_target exists, we can rename
203                bb.note('%s: Rename (link) %s -> %s' % (pn, alt_target, alt_target_rename))
204                bb.utils.rename(src, dest)
205            else:
206                # Try to resolve the broken link to link.${BPN}
207                link_maybe = '%s.%s' % (os.readlink(src), pn)
208                if os.path.lexists(os.path.join(os.path.dirname(src), link_maybe)):
209                    # Ok, the renamed link target exists.. create a new link, and remove the original
210                    bb.note('%s: Creating new link %s -> %s' % (pn, alt_target_rename, link_maybe))
211                    os.symlink(link_maybe, dest)
212                    os.unlink(src)
213                else:
214                    bb.warn('%s: Unable to resolve dangling symlink: %s' % (pn, alt_target))
215                    continue
216            update_files(alt_target, alt_target_rename, pkg, d)
217}
218
219def update_alternatives_alt_targets(d, pkg):
220    """
221    Returns the update-alternatives metadata for a package.
222
223    The returned format is a list of tuples where the tuple contains:
224    alt_name:     The binary name
225    alt_link:     The path for the binary (Shared by different packages)
226    alt_target:   The path for the renamed binary (Unique per package)
227    alt_priority: The priority of the alt_target
228
229    All the alt_targets will be installed into the sysroot. The alt_link is
230    a symlink pointing to the alt_target with the highest priority.
231    """
232
233    pn = d.getVar('BPN')
234    pkgdest = d.getVar('PKGD')
235    updates = list()
236    for alt_name in (d.getVar('ALTERNATIVE:%s' % pkg) or "").split():
237        alt_link     = d.getVarFlag('ALTERNATIVE_LINK_NAME', alt_name)
238        alt_target   = d.getVarFlag('ALTERNATIVE_TARGET_%s' % pkg, alt_name) or \
239                       d.getVarFlag('ALTERNATIVE_TARGET', alt_name) or \
240                       d.getVar('ALTERNATIVE_TARGET_%s' % pkg) or \
241                       d.getVar('ALTERNATIVE_TARGET') or \
242                       alt_link
243        alt_priority = d.getVarFlag('ALTERNATIVE_PRIORITY_%s' % pkg,  alt_name) or \
244                       d.getVarFlag('ALTERNATIVE_PRIORITY',  alt_name) or \
245                       d.getVar('ALTERNATIVE_PRIORITY_%s' % pkg) or  \
246                       d.getVar('ALTERNATIVE_PRIORITY')
247
248        # This shouldn't trigger, as it should have been resolved earlier!
249        if alt_link == alt_target:
250            bb.note('alt_link == alt_target: %s == %s -- correcting, this should not happen!' % (alt_link, alt_target))
251            alt_target = '%s.%s' % (alt_target, pn)
252
253        if not os.path.lexists('%s/%s' % (pkgdest, alt_target)):
254            bb.warn('%s: NOT adding alternative provide %s: %s does not exist' % (pn, alt_link, alt_target))
255            continue
256
257        alt_target = os.path.normpath(alt_target)
258        updates.append( (alt_name, alt_link, alt_target, alt_priority) )
259
260    return updates
261
262PACKAGESPLITFUNCS:prepend = "populate_packages_updatealternatives "
263
264python populate_packages_updatealternatives () {
265    if not update_alternatives_enabled(d):
266        return
267
268    # Do actual update alternatives processing
269    for pkg in (d.getVar('PACKAGES') or "").split():
270        # Create post install/removal scripts
271        alt_setup_links = ""
272        alt_remove_links = ""
273        updates = update_alternatives_alt_targets(d, pkg)
274        for alt_name, alt_link, alt_target, alt_priority in updates:
275            alt_setup_links  += '\tupdate-alternatives --install %s %s %s %s\n' % (alt_link, alt_name, alt_target, alt_priority)
276            alt_remove_links += '\tupdate-alternatives --remove  %s %s\n' % (alt_name, alt_target)
277
278        if alt_setup_links:
279            # RDEPENDS setup
280            provider = d.getVar('VIRTUAL-RUNTIME_update-alternatives')
281            if provider:
282                #bb.note('adding runtime requirement for update-alternatives for %s' % pkg)
283                d.appendVar('RDEPENDS:%s' % pkg, ' ' + d.getVar('MLPREFIX', False) + provider)
284
285            bb.note('adding update-alternatives calls to postinst/prerm for %s' % pkg)
286            bb.note('%s' % alt_setup_links)
287            postinst = d.getVar('pkg_postinst:%s' % pkg)
288            if postinst:
289                postinst = alt_setup_links + postinst
290            else:
291                postinst = '#!/bin/sh\n' + alt_setup_links
292            d.setVar('pkg_postinst:%s' % pkg, postinst)
293
294            bb.note('%s' % alt_remove_links)
295            prerm = d.getVar('pkg_prerm:%s' % pkg) or '#!/bin/sh\n'
296            prerm += alt_remove_links
297            d.setVar('pkg_prerm:%s' % pkg, prerm)
298}
299
300python package_do_filedeps:append () {
301    if update_alternatives_enabled(d):
302        apply_update_alternative_provides(d)
303}
304
305def apply_update_alternative_provides(d):
306    pn = d.getVar('BPN')
307    pkgdest = d.getVar('PKGDEST')
308
309    for pkg in d.getVar('PACKAGES').split():
310        for alt_name in (d.getVar('ALTERNATIVE:%s' % pkg) or "").split():
311            alt_link     = d.getVarFlag('ALTERNATIVE_LINK_NAME', alt_name)
312            alt_target   = d.getVarFlag('ALTERNATIVE_TARGET_%s' % pkg, alt_name) or d.getVarFlag('ALTERNATIVE_TARGET', alt_name)
313            alt_target   = alt_target or d.getVar('ALTERNATIVE_TARGET_%s' % pkg) or d.getVar('ALTERNATIVE_TARGET') or alt_link
314
315            if alt_link == alt_target:
316                bb.warn('%s: alt_link == alt_target: %s == %s' % (pn, alt_link, alt_target))
317                alt_target = '%s.%s' % (alt_target, pn)
318
319            if not os.path.lexists('%s/%s/%s' % (pkgdest, pkg, alt_target)):
320                continue
321
322            # Add file provide
323            trans_target = oe.package.file_translate(alt_target)
324            d.appendVar('FILERPROVIDES:%s:%s' % (trans_target, pkg), " " + alt_link)
325            if not trans_target in (d.getVar('FILERPROVIDESFLIST:%s' % pkg) or ""):
326                d.appendVar('FILERPROVIDESFLIST:%s' % pkg, " " + trans_target)
327
328