Juju Charm - Ceph OSD
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ubuntu.py 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. # Copyright 2014-2015 Canonical Limited.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections import OrderedDict
  15. import os
  16. import platform
  17. import re
  18. import six
  19. import time
  20. import subprocess
  21. from tempfile import NamedTemporaryFile
  22. from charmhelpers.core.host import (
  23. lsb_release
  24. )
  25. from charmhelpers.core.hookenv import (
  26. log,
  27. DEBUG,
  28. WARNING,
  29. )
  30. from charmhelpers.fetch import SourceConfigError, GPGKeyError
  31. PROPOSED_POCKET = (
  32. "# Proposed\n"
  33. "deb http://archive.ubuntu.com/ubuntu {}-proposed main universe "
  34. "multiverse restricted\n")
  35. PROPOSED_PORTS_POCKET = (
  36. "# Proposed\n"
  37. "deb http://ports.ubuntu.com/ubuntu-ports {}-proposed main universe "
  38. "multiverse restricted\n")
  39. # Only supports 64bit and ppc64 at the moment.
  40. ARCH_TO_PROPOSED_POCKET = {
  41. 'x86_64': PROPOSED_POCKET,
  42. 'ppc64le': PROPOSED_PORTS_POCKET,
  43. 'aarch64': PROPOSED_PORTS_POCKET,
  44. 's390x': PROPOSED_PORTS_POCKET,
  45. }
  46. CLOUD_ARCHIVE_URL = "http://ubuntu-cloud.archive.canonical.com/ubuntu"
  47. CLOUD_ARCHIVE_KEY_ID = '5EDB1B62EC4926EA'
  48. CLOUD_ARCHIVE = """# Ubuntu Cloud Archive
  49. deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main
  50. """
  51. CLOUD_ARCHIVE_POCKETS = {
  52. # Folsom
  53. 'folsom': 'precise-updates/folsom',
  54. 'folsom/updates': 'precise-updates/folsom',
  55. 'precise-folsom': 'precise-updates/folsom',
  56. 'precise-folsom/updates': 'precise-updates/folsom',
  57. 'precise-updates/folsom': 'precise-updates/folsom',
  58. 'folsom/proposed': 'precise-proposed/folsom',
  59. 'precise-folsom/proposed': 'precise-proposed/folsom',
  60. 'precise-proposed/folsom': 'precise-proposed/folsom',
  61. # Grizzly
  62. 'grizzly': 'precise-updates/grizzly',
  63. 'grizzly/updates': 'precise-updates/grizzly',
  64. 'precise-grizzly': 'precise-updates/grizzly',
  65. 'precise-grizzly/updates': 'precise-updates/grizzly',
  66. 'precise-updates/grizzly': 'precise-updates/grizzly',
  67. 'grizzly/proposed': 'precise-proposed/grizzly',
  68. 'precise-grizzly/proposed': 'precise-proposed/grizzly',
  69. 'precise-proposed/grizzly': 'precise-proposed/grizzly',
  70. # Havana
  71. 'havana': 'precise-updates/havana',
  72. 'havana/updates': 'precise-updates/havana',
  73. 'precise-havana': 'precise-updates/havana',
  74. 'precise-havana/updates': 'precise-updates/havana',
  75. 'precise-updates/havana': 'precise-updates/havana',
  76. 'havana/proposed': 'precise-proposed/havana',
  77. 'precise-havana/proposed': 'precise-proposed/havana',
  78. 'precise-proposed/havana': 'precise-proposed/havana',
  79. # Icehouse
  80. 'icehouse': 'precise-updates/icehouse',
  81. 'icehouse/updates': 'precise-updates/icehouse',
  82. 'precise-icehouse': 'precise-updates/icehouse',
  83. 'precise-icehouse/updates': 'precise-updates/icehouse',
  84. 'precise-updates/icehouse': 'precise-updates/icehouse',
  85. 'icehouse/proposed': 'precise-proposed/icehouse',
  86. 'precise-icehouse/proposed': 'precise-proposed/icehouse',
  87. 'precise-proposed/icehouse': 'precise-proposed/icehouse',
  88. # Juno
  89. 'juno': 'trusty-updates/juno',
  90. 'juno/updates': 'trusty-updates/juno',
  91. 'trusty-juno': 'trusty-updates/juno',
  92. 'trusty-juno/updates': 'trusty-updates/juno',
  93. 'trusty-updates/juno': 'trusty-updates/juno',
  94. 'juno/proposed': 'trusty-proposed/juno',
  95. 'trusty-juno/proposed': 'trusty-proposed/juno',
  96. 'trusty-proposed/juno': 'trusty-proposed/juno',
  97. # Kilo
  98. 'kilo': 'trusty-updates/kilo',
  99. 'kilo/updates': 'trusty-updates/kilo',
  100. 'trusty-kilo': 'trusty-updates/kilo',
  101. 'trusty-kilo/updates': 'trusty-updates/kilo',
  102. 'trusty-updates/kilo': 'trusty-updates/kilo',
  103. 'kilo/proposed': 'trusty-proposed/kilo',
  104. 'trusty-kilo/proposed': 'trusty-proposed/kilo',
  105. 'trusty-proposed/kilo': 'trusty-proposed/kilo',
  106. # Liberty
  107. 'liberty': 'trusty-updates/liberty',
  108. 'liberty/updates': 'trusty-updates/liberty',
  109. 'trusty-liberty': 'trusty-updates/liberty',
  110. 'trusty-liberty/updates': 'trusty-updates/liberty',
  111. 'trusty-updates/liberty': 'trusty-updates/liberty',
  112. 'liberty/proposed': 'trusty-proposed/liberty',
  113. 'trusty-liberty/proposed': 'trusty-proposed/liberty',
  114. 'trusty-proposed/liberty': 'trusty-proposed/liberty',
  115. # Mitaka
  116. 'mitaka': 'trusty-updates/mitaka',
  117. 'mitaka/updates': 'trusty-updates/mitaka',
  118. 'trusty-mitaka': 'trusty-updates/mitaka',
  119. 'trusty-mitaka/updates': 'trusty-updates/mitaka',
  120. 'trusty-updates/mitaka': 'trusty-updates/mitaka',
  121. 'mitaka/proposed': 'trusty-proposed/mitaka',
  122. 'trusty-mitaka/proposed': 'trusty-proposed/mitaka',
  123. 'trusty-proposed/mitaka': 'trusty-proposed/mitaka',
  124. # Newton
  125. 'newton': 'xenial-updates/newton',
  126. 'newton/updates': 'xenial-updates/newton',
  127. 'xenial-newton': 'xenial-updates/newton',
  128. 'xenial-newton/updates': 'xenial-updates/newton',
  129. 'xenial-updates/newton': 'xenial-updates/newton',
  130. 'newton/proposed': 'xenial-proposed/newton',
  131. 'xenial-newton/proposed': 'xenial-proposed/newton',
  132. 'xenial-proposed/newton': 'xenial-proposed/newton',
  133. # Ocata
  134. 'ocata': 'xenial-updates/ocata',
  135. 'ocata/updates': 'xenial-updates/ocata',
  136. 'xenial-ocata': 'xenial-updates/ocata',
  137. 'xenial-ocata/updates': 'xenial-updates/ocata',
  138. 'xenial-updates/ocata': 'xenial-updates/ocata',
  139. 'ocata/proposed': 'xenial-proposed/ocata',
  140. 'xenial-ocata/proposed': 'xenial-proposed/ocata',
  141. 'xenial-proposed/ocata': 'xenial-proposed/ocata',
  142. # Pike
  143. 'pike': 'xenial-updates/pike',
  144. 'xenial-pike': 'xenial-updates/pike',
  145. 'xenial-pike/updates': 'xenial-updates/pike',
  146. 'xenial-updates/pike': 'xenial-updates/pike',
  147. 'pike/proposed': 'xenial-proposed/pike',
  148. 'xenial-pike/proposed': 'xenial-proposed/pike',
  149. 'xenial-proposed/pike': 'xenial-proposed/pike',
  150. # Queens
  151. 'queens': 'xenial-updates/queens',
  152. 'xenial-queens': 'xenial-updates/queens',
  153. 'xenial-queens/updates': 'xenial-updates/queens',
  154. 'xenial-updates/queens': 'xenial-updates/queens',
  155. 'queens/proposed': 'xenial-proposed/queens',
  156. 'xenial-queens/proposed': 'xenial-proposed/queens',
  157. 'xenial-proposed/queens': 'xenial-proposed/queens',
  158. # Rocky
  159. 'rocky': 'bionic-updates/rocky',
  160. 'bionic-rocky': 'bionic-updates/rocky',
  161. 'bionic-rocky/updates': 'bionic-updates/rocky',
  162. 'bionic-updates/rocky': 'bionic-updates/rocky',
  163. 'rocky/proposed': 'bionic-proposed/rocky',
  164. 'bionic-rocky/proposed': 'bionic-proposed/rocky',
  165. 'bionic-proposed/rocky': 'bionic-proposed/rocky',
  166. }
  167. APT_NO_LOCK = 100 # The return code for "couldn't acquire lock" in APT.
  168. CMD_RETRY_DELAY = 10 # Wait 10 seconds between command retries.
  169. CMD_RETRY_COUNT = 3 # Retry a failing fatal command X times.
  170. def filter_installed_packages(packages):
  171. """Return a list of packages that require installation."""
  172. cache = apt_cache()
  173. _pkgs = []
  174. for package in packages:
  175. try:
  176. p = cache[package]
  177. p.current_ver or _pkgs.append(package)
  178. except KeyError:
  179. log('Package {} has no installation candidate.'.format(package),
  180. level='WARNING')
  181. _pkgs.append(package)
  182. return _pkgs
  183. def apt_cache(in_memory=True, progress=None):
  184. """Build and return an apt cache."""
  185. from apt import apt_pkg
  186. apt_pkg.init()
  187. if in_memory:
  188. apt_pkg.config.set("Dir::Cache::pkgcache", "")
  189. apt_pkg.config.set("Dir::Cache::srcpkgcache", "")
  190. return apt_pkg.Cache(progress)
  191. def apt_install(packages, options=None, fatal=False):
  192. """Install one or more packages."""
  193. if options is None:
  194. options = ['--option=Dpkg::Options::=--force-confold']
  195. cmd = ['apt-get', '--assume-yes']
  196. cmd.extend(options)
  197. cmd.append('install')
  198. if isinstance(packages, six.string_types):
  199. cmd.append(packages)
  200. else:
  201. cmd.extend(packages)
  202. log("Installing {} with options: {}".format(packages,
  203. options))
  204. _run_apt_command(cmd, fatal)
  205. def apt_upgrade(options=None, fatal=False, dist=False):
  206. """Upgrade all packages."""
  207. if options is None:
  208. options = ['--option=Dpkg::Options::=--force-confold']
  209. cmd = ['apt-get', '--assume-yes']
  210. cmd.extend(options)
  211. if dist:
  212. cmd.append('dist-upgrade')
  213. else:
  214. cmd.append('upgrade')
  215. log("Upgrading with options: {}".format(options))
  216. _run_apt_command(cmd, fatal)
  217. def apt_update(fatal=False):
  218. """Update local apt cache."""
  219. cmd = ['apt-get', 'update']
  220. _run_apt_command(cmd, fatal)
  221. def apt_purge(packages, fatal=False):
  222. """Purge one or more packages."""
  223. cmd = ['apt-get', '--assume-yes', 'purge']
  224. if isinstance(packages, six.string_types):
  225. cmd.append(packages)
  226. else:
  227. cmd.extend(packages)
  228. log("Purging {}".format(packages))
  229. _run_apt_command(cmd, fatal)
  230. def apt_mark(packages, mark, fatal=False):
  231. """Flag one or more packages using apt-mark."""
  232. log("Marking {} as {}".format(packages, mark))
  233. cmd = ['apt-mark', mark]
  234. if isinstance(packages, six.string_types):
  235. cmd.append(packages)
  236. else:
  237. cmd.extend(packages)
  238. if fatal:
  239. subprocess.check_call(cmd, universal_newlines=True)
  240. else:
  241. subprocess.call(cmd, universal_newlines=True)
  242. def apt_hold(packages, fatal=False):
  243. return apt_mark(packages, 'hold', fatal=fatal)
  244. def apt_unhold(packages, fatal=False):
  245. return apt_mark(packages, 'unhold', fatal=fatal)
  246. def import_key(key):
  247. """Import an ASCII Armor key.
  248. /!\ A Radix64 format keyid is also supported for backwards
  249. compatibility, but should never be used; the key retrieval
  250. mechanism is insecure and subject to man-in-the-middle attacks
  251. voiding all signature checks using that key.
  252. :param keyid: The key in ASCII armor format,
  253. including BEGIN and END markers.
  254. :raises: GPGKeyError if the key could not be imported
  255. """
  256. key = key.strip()
  257. if '-' in key or '\n' in key:
  258. # Send everything not obviously a keyid to GPG to import, as
  259. # we trust its validation better than our own. eg. handling
  260. # comments before the key.
  261. log("PGP key found (looks like ASCII Armor format)", level=DEBUG)
  262. if ('-----BEGIN PGP PUBLIC KEY BLOCK-----' in key and
  263. '-----END PGP PUBLIC KEY BLOCK-----' in key):
  264. log("Importing ASCII Armor PGP key", level=DEBUG)
  265. with NamedTemporaryFile() as keyfile:
  266. with open(keyfile.name, 'w') as fd:
  267. fd.write(key)
  268. fd.write("\n")
  269. cmd = ['apt-key', 'add', keyfile.name]
  270. try:
  271. subprocess.check_call(cmd)
  272. except subprocess.CalledProcessError:
  273. error = "Error importing PGP key '{}'".format(key)
  274. log(error)
  275. raise GPGKeyError(error)
  276. else:
  277. raise GPGKeyError("ASCII armor markers missing from GPG key")
  278. else:
  279. # We should only send things obviously not a keyid offsite
  280. # via this unsecured protocol, as it may be a secret or part
  281. # of one.
  282. log("PGP key found (looks like Radix64 format)", level=WARNING)
  283. log("INSECURLY importing PGP key from keyserver; "
  284. "full key not provided.", level=WARNING)
  285. cmd = ['apt-key', 'adv', '--keyserver',
  286. 'hkp://keyserver.ubuntu.com:80', '--recv-keys', key]
  287. try:
  288. subprocess.check_call(cmd)
  289. except subprocess.CalledProcessError:
  290. error = "Error importing PGP key '{}'".format(key)
  291. log(error)
  292. raise GPGKeyError(error)
  293. def add_source(source, key=None, fail_invalid=False):
  294. """Add a package source to this system.
  295. @param source: a URL or sources.list entry, as supported by
  296. add-apt-repository(1). Examples::
  297. ppa:charmers/example
  298. deb https://stub:key@private.example.com/ubuntu trusty main
  299. In addition:
  300. 'proposed:' may be used to enable the standard 'proposed'
  301. pocket for the release.
  302. 'cloud:' may be used to activate official cloud archive pockets,
  303. such as 'cloud:icehouse'
  304. 'distro' may be used as a noop
  305. Full list of source specifications supported by the function are:
  306. 'distro': A NOP; i.e. it has no effect.
  307. 'proposed': the proposed deb spec [2] is wrtten to
  308. /etc/apt/sources.list/proposed
  309. 'distro-proposed': adds <version>-proposed to the debs [2]
  310. 'ppa:<ppa-name>': add-apt-repository --yes <ppa_name>
  311. 'deb <deb-spec>': add-apt-repository --yes deb <deb-spec>
  312. 'http://....': add-apt-repository --yes http://...
  313. 'cloud-archive:<spec>': add-apt-repository -yes cloud-archive:<spec>
  314. 'cloud:<release>[-staging]': specify a Cloud Archive pocket <release> with
  315. optional staging version. If staging is used then the staging PPA [2]
  316. with be used. If staging is NOT used then the cloud archive [3] will be
  317. added, and the 'ubuntu-cloud-keyring' package will be added for the
  318. current distro.
  319. Otherwise the source is not recognised and this is logged to the juju log.
  320. However, no error is raised, unless sys_error_on_exit is True.
  321. [1] deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main
  322. where {} is replaced with the derived pocket name.
  323. [2] deb http://archive.ubuntu.com/ubuntu {}-proposed \
  324. main universe multiverse restricted
  325. where {} is replaced with the lsb_release codename (e.g. xenial)
  326. [3] deb http://ubuntu-cloud.archive.canonical.com/ubuntu <pocket>
  327. to /etc/apt/sources.list.d/cloud-archive-list
  328. @param key: A key to be added to the system's APT keyring and used
  329. to verify the signatures on packages. Ideally, this should be an
  330. ASCII format GPG public key including the block headers. A GPG key
  331. id may also be used, but be aware that only insecure protocols are
  332. available to retrieve the actual public key from a public keyserver
  333. placing your Juju environment at risk. ppa and cloud archive keys
  334. are securely added automtically, so sould not be provided.
  335. @param fail_invalid: (boolean) if True, then the function raises a
  336. SourceConfigError is there is no matching installation source.
  337. @raises SourceConfigError() if for cloud:<pocket>, the <pocket> is not a
  338. valid pocket in CLOUD_ARCHIVE_POCKETS
  339. """
  340. _mapping = OrderedDict([
  341. (r"^distro$", lambda: None), # This is a NOP
  342. (r"^(?:proposed|distro-proposed)$", _add_proposed),
  343. (r"^cloud-archive:(.*)$", _add_apt_repository),
  344. (r"^((?:deb |http:|https:|ppa:).*)$", _add_apt_repository),
  345. (r"^cloud:(.*)-(.*)\/staging$", _add_cloud_staging),
  346. (r"^cloud:(.*)-(.*)$", _add_cloud_distro_check),
  347. (r"^cloud:(.*)$", _add_cloud_pocket),
  348. (r"^snap:.*-(.*)-(.*)$", _add_cloud_distro_check),
  349. ])
  350. if source is None:
  351. source = ''
  352. for r, fn in six.iteritems(_mapping):
  353. m = re.match(r, source)
  354. if m:
  355. # call the assoicated function with the captured groups
  356. # raises SourceConfigError on error.
  357. fn(*m.groups())
  358. if key:
  359. try:
  360. import_key(key)
  361. except GPGKeyError as e:
  362. raise SourceConfigError(str(e))
  363. break
  364. else:
  365. # nothing matched. log an error and maybe sys.exit
  366. err = "Unknown source: {!r}".format(source)
  367. log(err)
  368. if fail_invalid:
  369. raise SourceConfigError(err)
  370. def _add_proposed():
  371. """Add the PROPOSED_POCKET as /etc/apt/source.list.d/proposed.list
  372. Uses lsb_release()['DISTRIB_CODENAME'] to determine the correct staza for
  373. the deb line.
  374. For intel architecutres PROPOSED_POCKET is used for the release, but for
  375. other architectures PROPOSED_PORTS_POCKET is used for the release.
  376. """
  377. release = lsb_release()['DISTRIB_CODENAME']
  378. arch = platform.machine()
  379. if arch not in six.iterkeys(ARCH_TO_PROPOSED_POCKET):
  380. raise SourceConfigError("Arch {} not supported for (distro-)proposed"
  381. .format(arch))
  382. with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt:
  383. apt.write(ARCH_TO_PROPOSED_POCKET[arch].format(release))
  384. def _add_apt_repository(spec):
  385. """Add the spec using add_apt_repository
  386. :param spec: the parameter to pass to add_apt_repository
  387. """
  388. _run_with_retries(['add-apt-repository', '--yes', spec])
  389. def _add_cloud_pocket(pocket):
  390. """Add a cloud pocket as /etc/apt/sources.d/cloud-archive.list
  391. Note that this overwrites the existing file if there is one.
  392. This function also converts the simple pocket in to the actual pocket using
  393. the CLOUD_ARCHIVE_POCKETS mapping.
  394. :param pocket: string representing the pocket to add a deb spec for.
  395. :raises: SourceConfigError if the cloud pocket doesn't exist or the
  396. requested release doesn't match the current distro version.
  397. """
  398. apt_install(filter_installed_packages(['ubuntu-cloud-keyring']),
  399. fatal=True)
  400. if pocket not in CLOUD_ARCHIVE_POCKETS:
  401. raise SourceConfigError(
  402. 'Unsupported cloud: source option %s' %
  403. pocket)
  404. actual_pocket = CLOUD_ARCHIVE_POCKETS[pocket]
  405. with open('/etc/apt/sources.list.d/cloud-archive.list', 'w') as apt:
  406. apt.write(CLOUD_ARCHIVE.format(actual_pocket))
  407. def _add_cloud_staging(cloud_archive_release, openstack_release):
  408. """Add the cloud staging repository which is in
  409. ppa:ubuntu-cloud-archive/<openstack_release>-staging
  410. This function checks that the cloud_archive_release matches the current
  411. codename for the distro that charm is being installed on.
  412. :param cloud_archive_release: string, codename for the release.
  413. :param openstack_release: String, codename for the openstack release.
  414. :raises: SourceConfigError if the cloud_archive_release doesn't match the
  415. current version of the os.
  416. """
  417. _verify_is_ubuntu_rel(cloud_archive_release, openstack_release)
  418. ppa = 'ppa:ubuntu-cloud-archive/{}-staging'.format(openstack_release)
  419. cmd = 'add-apt-repository -y {}'.format(ppa)
  420. _run_with_retries(cmd.split(' '))
  421. def _add_cloud_distro_check(cloud_archive_release, openstack_release):
  422. """Add the cloud pocket, but also check the cloud_archive_release against
  423. the current distro, and use the openstack_release as the full lookup.
  424. This just calls _add_cloud_pocket() with the openstack_release as pocket
  425. to get the correct cloud-archive.list for dpkg to work with.
  426. :param cloud_archive_release:String, codename for the distro release.
  427. :param openstack_release: String, spec for the release to look up in the
  428. CLOUD_ARCHIVE_POCKETS
  429. :raises: SourceConfigError if this is the wrong distro, or the pocket spec
  430. doesn't exist.
  431. """
  432. _verify_is_ubuntu_rel(cloud_archive_release, openstack_release)
  433. _add_cloud_pocket("{}-{}".format(cloud_archive_release, openstack_release))
  434. def _verify_is_ubuntu_rel(release, os_release):
  435. """Verify that the release is in the same as the current ubuntu release.
  436. :param release: String, lowercase for the release.
  437. :param os_release: String, the os_release being asked for
  438. :raises: SourceConfigError if the release is not the same as the ubuntu
  439. release.
  440. """
  441. ubuntu_rel = lsb_release()['DISTRIB_CODENAME']
  442. if release != ubuntu_rel:
  443. raise SourceConfigError(
  444. 'Invalid Cloud Archive release specified: {}-{} on this Ubuntu'
  445. 'version ({})'.format(release, os_release, ubuntu_rel))
  446. def _run_with_retries(cmd, max_retries=CMD_RETRY_COUNT, retry_exitcodes=(1,),
  447. retry_message="", cmd_env=None):
  448. """Run a command and retry until success or max_retries is reached.
  449. :param: cmd: str: The apt command to run.
  450. :param: max_retries: int: The number of retries to attempt on a fatal
  451. command. Defaults to CMD_RETRY_COUNT.
  452. :param: retry_exitcodes: tuple: Optional additional exit codes to retry.
  453. Defaults to retry on exit code 1.
  454. :param: retry_message: str: Optional log prefix emitted during retries.
  455. :param: cmd_env: dict: Environment variables to add to the command run.
  456. """
  457. env = None
  458. kwargs = {}
  459. if cmd_env:
  460. env = os.environ.copy()
  461. env.update(cmd_env)
  462. kwargs['env'] = env
  463. if not retry_message:
  464. retry_message = "Failed executing '{}'".format(" ".join(cmd))
  465. retry_message += ". Will retry in {} seconds".format(CMD_RETRY_DELAY)
  466. retry_count = 0
  467. result = None
  468. retry_results = (None,) + retry_exitcodes
  469. while result in retry_results:
  470. try:
  471. # result = subprocess.check_call(cmd, env=env)
  472. result = subprocess.check_call(cmd, **kwargs)
  473. except subprocess.CalledProcessError as e:
  474. retry_count = retry_count + 1
  475. if retry_count > max_retries:
  476. raise
  477. result = e.returncode
  478. log(retry_message)
  479. time.sleep(CMD_RETRY_DELAY)
  480. def _run_apt_command(cmd, fatal=False):
  481. """Run an apt command with optional retries.
  482. :param: cmd: str: The apt command to run.
  483. :param: fatal: bool: Whether the command's output should be checked and
  484. retried.
  485. """
  486. # Provide DEBIAN_FRONTEND=noninteractive if not present in the environment.
  487. cmd_env = {
  488. 'DEBIAN_FRONTEND': os.environ.get('DEBIAN_FRONTEND', 'noninteractive')}
  489. if fatal:
  490. _run_with_retries(
  491. cmd, cmd_env=cmd_env, retry_exitcodes=(1, APT_NO_LOCK,),
  492. retry_message="Couldn't acquire DPKG lock")
  493. else:
  494. env = os.environ.copy()
  495. env.update(cmd_env)
  496. subprocess.call(cmd, env=env)
  497. def get_upstream_version(package):
  498. """Determine upstream version based on installed package
  499. @returns None (if not installed) or the upstream version
  500. """
  501. import apt_pkg
  502. cache = apt_cache()
  503. try:
  504. pkg = cache[package]
  505. except Exception:
  506. # the package is unknown to the current apt cache.
  507. return None
  508. if not pkg.current_ver:
  509. # package is known, but no version is currently installed.
  510. return None
  511. return apt_pkg.upstream_version(pkg.current_ver.ver_str)