blob: f0052c10491ac5d250884c80a0fd3b8fe9abc8b0 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -07002# Copyright 2014 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Install debug symbols for specified packages.
7
8Only reinstall the debug symbols if they are not already installed to save time.
9
10The debug symbols are packaged outside of the prebuilt package in a
11.debug.tbz2 archive when FEATURES=separatedebug is set (by default on
12builders). On local machines, separatedebug is not set and the debug symbols
13are part of the prebuilt package.
14"""
15
16from __future__ import print_function
17
18import argparse
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -070019import os
20import pickle
21import sys
22import tempfile
Bertrand SIMONNET8e537282014-12-04 15:04:42 -080023import urlparse
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -070024
25from chromite.lib import binpkg
26from chromite.lib import cache
27from chromite.lib import commandline
28from chromite.lib import cros_build_lib
Ralph Nathan91874ca2015-03-19 13:29:41 -070029from chromite.lib import cros_logging as logging
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -070030from chromite.lib import osutils
31from chromite.lib import parallel
Gilad Arnold83233ed2015-05-08 12:12:13 -070032from chromite.lib import path_util
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -070033from chromite.lib import gs
Bertrand SIMONNET01394c32015-02-09 17:20:25 -080034
35if cros_build_lib.IsInsideChroot():
36 from portage import create_trees
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -070037
38
39DEBUG_SYMS_EXT = '.debug.tbz2'
40
41
Bertrand SIMONNET1e146e52014-12-11 14:11:56 -080042# We cache the package indexes. When the format of what we store changes,
43# bump the cache version to avoid problems.
44CACHE_VERSION = '1'
45
46
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -070047class DebugSymbolsInstaller(object):
48 """Container for enviromnent objects, needed to make multiprocessing work.
49
50 This also redirects stdout to null when stdout_to_null=True to avoid
51 polluting the output with portage QA warnings.
52 """
53 _old_stdout = None
54 _null = None
55
56 def __init__(self, vartree, gs_context, sysroot, stdout_to_null):
57 self._vartree = vartree
58 self._gs_context = gs_context
59 self._sysroot = sysroot
60 self._stdout_to_null = stdout_to_null
61
62 def __enter__(self):
63 if self._stdout_to_null:
64 self._old_stdout = sys.stdout
65 self._null = open(os.devnull, 'w')
66 sys.stdout = self._null
67 return self
68
69 def __exit__(self, _exc_type, _exc_val, _exc_tb):
70 if self._stdout_to_null:
71 sys.stdout = self._old_stdout
72 self._null.close()
73
74 def Install(self, cpv, url):
75 """Install the debug symbols for |cpv|.
76
77 This will install the debug symbols tarball in PKGDIR so that it can be
78 used later.
79
80 Args:
81 cpv: the cpv of the package to build. This assumes that the cpv is
82 installed in the sysroot.
83 url: url of the debug symbols archive. This could be a Google Storage url
84 or a local path.
85 """
86 archive = os.path.join(self._vartree.settings['PKGDIR'],
87 cpv + DEBUG_SYMS_EXT)
Bertrand SIMONNET1e146e52014-12-11 14:11:56 -080088 # GsContext does not understand file:// scheme so we need to extract the
89 # path ourselves.
90 parsed_url = urlparse.urlsplit(url)
91 if not parsed_url.scheme or parsed_url.scheme == 'file':
92 url = parsed_url.path
93
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -070094 if not os.path.isfile(archive):
95 self._gs_context.Copy(url, archive, debug_level=logging.DEBUG)
96
97 with osutils.TempDir(sudo_rm=True) as tempdir:
98 cros_build_lib.SudoRunCommand(['tar', '-I', 'bzip2 -q', '-xf', archive,
99 '-C', tempdir], quiet=True)
100
101 with open(self._vartree.getpath(cpv, filename='CONTENTS'),
102 'a') as content_file:
103 # Merge the content of the temporary dir into the sysroot.
104 # pylint: disable=protected-access
105 link = self._vartree.dbapi._dblink(cpv)
106 link.mergeme(tempdir, self._sysroot, content_file, None, '', {}, None)
107
108
109def ParseArgs(argv):
110 """Parse arguments and initialize field.
111
112 Args:
113 argv: arguments passed to the script.
114 """
115 parser = commandline.ArgumentParser(description=__doc__)
116 parser.add_argument('--board', help='Board name (required).', required=True)
117 parser.add_argument('--all', dest='all', action='store_true',
118 help='Install the debug symbols for all installed '
119 'packages', default=False)
120 parser.add_argument('packages', nargs=argparse.REMAINDER,
121 help='list of packages that need the debug symbols.')
122
123 advanced = parser.add_argument_group('Advanced options')
124 advanced.add_argument('--nocachebinhost', dest='cachebinhost', default=True,
125 action='store_false', help="Don't cache the list of"
126 " files contained in binhosts. (Default: cache)")
127 advanced.add_argument('--clearcache', dest='clearcache', action='store_true',
128 default=False, help='Clear the binhost cache.')
129 advanced.add_argument('--jobs', default=None, type=int,
130 help='Number of processes to run in parallel.')
131
132 options = parser.parse_args(argv)
133 options.Freeze()
134
135 if options.all and options.packages:
136 cros_build_lib.Die('Cannot use --all with a list of packages')
137 return options
138
139
140def ShouldGetSymbols(cpv, vardb, remote_symbols):
141 """Return True if the symbols for cpv are available and are not installed.
142
143 We try to check if the symbols are installed before checking availability as
144 a GS request is more expensive than checking locally.
145
146 Args:
147 cpv: cpv of the package
148 vardb: a vartree dbapi
149 remote_symbols: a mapping from cpv to debug symbols url
150
151 Returns:
152 True if |cpv|'s debug symbols are not installed and are available
153 """
154 features, contents = vardb.aux_get(cpv, ['FEATURES', 'CONTENTS'])
155
156 return ('separatedebug' in features and not '/usr/lib/debug/' in contents
157 and cpv in remote_symbols)
158
159
160def RemoteSymbols(vartree, binhost_cache=None):
161 """Get the cpv to debug symbols mapping.
162
163 If several binhost contain debug symbols for the same cpv, keep only the
164 highest priority one.
165
166 Args:
167 vartree: a vartree
168 binhost_cache: a cache containing the cpv to debug symbols url for all
169 known binhosts. None if we are not caching binhosts.
170
171 Returns:
172 a dictionary mapping the cpv to a remote debug symbols gsurl.
173 """
174 symbols_mapping = {}
175 for binhost in vartree.settings['PORTAGE_BINHOST'].split():
176 if binhost:
177 symbols_mapping.update(ListBinhost(binhost, binhost_cache))
178 return symbols_mapping
179
180
Bertrand SIMONNET1e146e52014-12-11 14:11:56 -0800181def GetPackageIndex(binhost, binhost_cache=None):
182 """Get the packages index for |binhost|.
183
184 If a cache is provided, use it to a cache remote packages index.
185
186 Args:
187 binhost: a portage binhost, local, google storage or http.
188 binhost_cache: a cache for the remote packages index.
189
190 Returns:
191 A PackageIndex object.
192 """
193 key = binhost.split('://')[-1]
194 key = key.rstrip('/').split('/')
195
196 if binhost_cache and binhost_cache.Lookup(key).Exists():
197 with open(binhost_cache.Lookup(key).path) as f:
198 return pickle.load(f)
199
200 pkgindex = binpkg.GrabRemotePackageIndex(binhost)
201 if pkgindex and binhost_cache:
202 # Only cache remote binhosts as local binhosts can change.
203 with tempfile.NamedTemporaryFile(delete=False) as temp_file:
204 pickle.dump(pkgindex, temp_file)
205 temp_file.file.close()
206 binhost_cache.Lookup(key).Assign(temp_file.name)
207 elif pkgindex is None:
Bertrand SIMONNETdd66ab52015-01-08 14:48:51 -0800208 urlparts = urlparse.urlsplit(binhost)
209 if urlparts.scheme not in ('file', ''):
210 # Don't fail the build on network errors. Print a warning message and
211 # continue.
Ralph Nathan446aee92015-03-23 14:44:56 -0700212 logging.warning('Could not get package index %s' % binhost)
Bertrand SIMONNETdd66ab52015-01-08 14:48:51 -0800213 return None
214
215 binhost = urlparts.path
Bertrand SIMONNET1e146e52014-12-11 14:11:56 -0800216 if not os.path.isdir(binhost):
217 raise ValueError('unrecognized binhost format for %s.')
218 pkgindex = binpkg.GrabLocalPackageIndex(binhost)
219
220 return pkgindex
221
222
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700223def ListBinhost(binhost, binhost_cache=None):
224 """Return the cpv to debug symbols mapping for a given binhost.
225
226 List the content of the binhost to extract the cpv to debug symbols
227 mapping. If --cachebinhost is set, we cache the result to avoid the
228 cost of gsutil every time.
229
230 Args:
231 binhost: a portage binhost, local or on google storage.
232 binhost_cache: a cache containing mappings cpv to debug symbols url for a
233 given binhost (None if we don't want to cache).
234
235 Returns:
236 A cpv to debug symbols url mapping.
237 """
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700238
239 symbols = {}
Bertrand SIMONNET1e146e52014-12-11 14:11:56 -0800240 pkgindex = GetPackageIndex(binhost, binhost_cache)
Bertrand SIMONNETdd66ab52015-01-08 14:48:51 -0800241 if pkgindex is None:
242 return symbols
243
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700244 for p in pkgindex.packages:
245 if p.get('DEBUG_SYMBOLS') == 'yes':
Bertrand SIMONNET1e146e52014-12-11 14:11:56 -0800246 path = p.get('PATH', p['CPV'] + '.tbz2')
247 base_url = pkgindex.header.get('URI', binhost)
248 symbols[p['CPV']] = os.path.join(base_url,
249 path.replace('.tbz2', DEBUG_SYMS_EXT))
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700250
251 return symbols
252
253
254def GetMatchingCPV(package, vardb):
255 """Return the cpv of the installed package matching |package|.
256
257 Args:
258 package: package name
259 vardb: a vartree dbapi
260
261 Returns:
262 The cpv of the installed package whose name matchex |package|.
263 """
264 matches = vardb.match(package)
265 if not matches:
266 cros_build_lib.Die('Could not find package %s' % package)
267 if len(matches) != 1:
268 cros_build_lib.Die('Ambiguous package name: %s.\n'
269 'Matching: %s' % (package, ' '.join(matches)))
270 return matches[0]
271
272
273def main(argv):
274 options = ParseArgs(argv)
275
Bertrand SIMONNET01394c32015-02-09 17:20:25 -0800276 if not cros_build_lib.IsInsideChroot():
277 raise commandline.ChrootRequiredError()
278
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700279 if os.geteuid() != 0:
Bertrand SIMONNET01394c32015-02-09 17:20:25 -0800280 cros_build_lib.SudoRunCommand(sys.argv)
281 return
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700282
283 # sysroot must have a trailing / as the tree dictionary produced by
284 # create_trees in indexed with a trailing /.
285 sysroot = cros_build_lib.GetSysroot(options.board) + '/'
286 trees = create_trees(target_root=sysroot, config_root=sysroot)
287
288 vartree = trees[sysroot]['vartree']
289
Gilad Arnold83233ed2015-05-08 12:12:13 -0700290 cache_dir = os.path.join(path_util.FindCacheDir(),
Bertrand SIMONNET1e146e52014-12-11 14:11:56 -0800291 'cros_install_debug_syms-v' + CACHE_VERSION)
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700292
293 if options.clearcache:
294 osutils.RmDir(cache_dir, ignore_missing=True)
295
296 binhost_cache = None
297 if options.cachebinhost:
298 binhost_cache = cache.DiskCache(cache_dir)
299
Bertrand SIMONNETbef192e2014-12-17 14:09:16 -0800300 boto_file = vartree.settings['BOTO_CONFIG']
301 if boto_file:
302 os.environ['BOTO_CONFIG'] = boto_file
303
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700304 gs_context = gs.GSContext()
305 symbols_mapping = RemoteSymbols(vartree, binhost_cache)
306
307 if options.all:
308 to_install = vartree.dbapi.cpv_all()
309 else:
310 to_install = [GetMatchingCPV(p, vartree.dbapi) for p in options.packages]
311
312 to_install = [p for p in to_install
313 if ShouldGetSymbols(p, vartree.dbapi, symbols_mapping)]
314
315 if not to_install:
Ralph Nathan03047282015-03-23 11:09:32 -0700316 logging.info('nothing to do, exit')
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700317 return
318
319 with DebugSymbolsInstaller(vartree, gs_context, sysroot,
320 not options.debug) as installer:
321 args = [(p, symbols_mapping[p]) for p in to_install]
322 parallel.RunTasksInProcessPool(installer.Install, args,
323 processes=options.jobs)
324
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700325 logging.debug('installation done, updating packages index file')
Bertrand SIMONNET6b6a1312014-10-29 18:37:51 -0700326 packages_dir = os.path.join(sysroot, 'packages')
327 packages_file = os.path.join(packages_dir, 'Packages')
328 # binpkg will set DEBUG_SYMBOLS automatically if it detects the debug symbols
329 # in the packages dir.
330 pkgindex = binpkg.GrabLocalPackageIndex(packages_dir)
331 with open(packages_file, 'w') as p:
332 pkgindex.Write(p)