Kolla provides production-ready containers and deployment tools for operating OpenStack clouds
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.

build.py 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  1. #!/usr/bin/env python
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. # See the License for the specific language governing permissions and
  12. # limitations under the License.
  13. from __future__ import print_function
  14. import contextlib
  15. import datetime
  16. import errno
  17. import json
  18. import logging
  19. import os
  20. import re
  21. import requests
  22. import shutil
  23. import sys
  24. import tarfile
  25. import tempfile
  26. import threading
  27. import time
  28. from distutils.version import StrictVersion
  29. import docker
  30. import git
  31. import jinja2
  32. from oslo_config import cfg
  33. from requests import exceptions as requests_exc
  34. import six
  35. # NOTE(SamYaple): Update the search path to prefer PROJECT_ROOT as the source
  36. # of packages to import if we are using local tools instead of
  37. # pip installed kolla tools
  38. PROJECT_ROOT = os.path.abspath(os.path.join(
  39. os.path.dirname(os.path.realpath(__file__)), '../..'))
  40. if PROJECT_ROOT not in sys.path:
  41. sys.path.insert(0, PROJECT_ROOT)
  42. from kolla.common import config as common_config
  43. from kolla.common import task
  44. from kolla.common import utils
  45. from kolla import exception
  46. from kolla.template import filters as jinja_filters
  47. from kolla.template import methods as jinja_methods
  48. from kolla import version
  49. LOG = utils.make_a_logger()
  50. # Image status constants.
  51. #
  52. # TODO(harlowja): use enum lib in the future??
  53. STATUS_CONNECTION_ERROR = 'connection_error'
  54. STATUS_PUSH_ERROR = 'push_error'
  55. STATUS_ERROR = 'error'
  56. STATUS_PARENT_ERROR = 'parent_error'
  57. STATUS_BUILT = 'built'
  58. STATUS_BUILDING = 'building'
  59. STATUS_UNMATCHED = 'unmatched'
  60. STATUS_MATCHED = 'matched'
  61. STATUS_UNPROCESSED = 'unprocessed'
  62. STATUS_SKIPPED = 'skipped'
  63. # All error status constants.
  64. STATUS_ERRORS = (STATUS_CONNECTION_ERROR, STATUS_PUSH_ERROR,
  65. STATUS_ERROR, STATUS_PARENT_ERROR)
  66. SKIPPED_IMAGES = {
  67. 'centos+binary': [
  68. "almanach-base",
  69. "bifrost-base",
  70. "blazar-base",
  71. "dragonflow-base",
  72. "freezer-base",
  73. "karbor-base",
  74. "kuryr-base",
  75. "monasca-base",
  76. "monasca-thresh",
  77. "nova-mksproxy",
  78. "ovsdpdk",
  79. "searchlight-base",
  80. "solum-base",
  81. "vmtp",
  82. "zun-base",
  83. ],
  84. 'centos+source': [
  85. "ovsdpdk",
  86. # TODO(jeffrey4l): remove tripleo-ui when following bug is fixed
  87. # https://bugs.launchpad.net/tripleo/+bug/1744215
  88. "tripleo-ui"
  89. ],
  90. 'ubuntu+binary': [
  91. "almanach-base",
  92. "bifrost-base",
  93. "blazar-base",
  94. "cloudkitty-base",
  95. "congress-base",
  96. "dragonflow-base",
  97. "ec2-api",
  98. "freezer-base",
  99. "heat-all",
  100. "ironic-neutron-agent",
  101. "karbor-base",
  102. "kuryr-base",
  103. "mistral-event-engine",
  104. "monasca-base",
  105. "monasca-thresh",
  106. "nova-mksproxy",
  107. "novajoin-base",
  108. "octavia-base",
  109. # There is no qdrouterd package for ubuntu bionic
  110. "qdrouterd",
  111. "searchlight-base",
  112. "solum-base",
  113. "tacker-base",
  114. "tripleo-ui",
  115. "vitrage-base",
  116. "vmtp",
  117. "zaqar",
  118. "zun-base",
  119. ],
  120. 'ubuntu+source': [
  121. # There is no qdrouterd package for ubuntu bionic
  122. "qdrouterd",
  123. # TODO(jeffrey4l): remove tripleo-ui when following bug is fixed
  124. # https://bugs.launchpad.net/tripleo/+bug/1744215
  125. "tripleo-ui"
  126. ],
  127. 'debian+binary': [
  128. "almanach-base",
  129. "bifrost-base",
  130. "blazar-base",
  131. "cloudkitty-base",
  132. "congress-base",
  133. "dragonflow-base",
  134. "ec2-api",
  135. "freezer-base",
  136. "heat-all",
  137. "ironic-neutron-agent",
  138. "karbor-base",
  139. "kuryr-base",
  140. "mistral-event-engine",
  141. "monasca-base",
  142. "monasca-thresh",
  143. "nova-mksproxy",
  144. "novajoin-base",
  145. "octavia-base",
  146. "searchlight-base",
  147. "sensu-base",
  148. "solum-base",
  149. "tacker-base",
  150. "tripleo-ui",
  151. "vitrage-base",
  152. "vmtp",
  153. "zaqar",
  154. "zun-base"
  155. ],
  156. 'debian+source': [
  157. "sensu-base",
  158. "tripleo-ui"
  159. ],
  160. 'oraclelinux+binary': [
  161. "almanach-base",
  162. "bifrost-base",
  163. "blazar-base",
  164. "dragonflow-base",
  165. "freezer-base",
  166. "karbor-base",
  167. "kuryr-base",
  168. "monasca-base",
  169. "monasca-thresh",
  170. "nova-mksproxy",
  171. "ovsdpdk",
  172. "searchlight-base",
  173. "solum-base",
  174. "vmtp",
  175. "zun-base"
  176. ],
  177. 'oraclelinux+source': [
  178. "bifrost-base",
  179. "ovsdpdk",
  180. # TODO(jeffrey4l): remove tripleo-ui when following bug is fixed
  181. # https://bugs.launchpad.net/tripleo/+bug/1744215
  182. "tripleo-ui"
  183. ]
  184. }
  185. class ArchivingError(Exception):
  186. pass
  187. @contextlib.contextmanager
  188. def join_many(threads):
  189. try:
  190. yield
  191. for t in threads:
  192. t.join()
  193. except KeyboardInterrupt:
  194. try:
  195. LOG.info('Waiting for daemon threads exit. Push Ctrl + c again to'
  196. ' force exit')
  197. for t in threads:
  198. if t.is_alive():
  199. LOG.debug('Waiting thread %s to exit', t.name)
  200. # NOTE(Jeffrey4l): Python Bug: When join without timeout,
  201. # KeyboardInterrupt is never sent.
  202. t.join(0xffff)
  203. LOG.debug('Thread %s exits', t.name)
  204. except KeyboardInterrupt:
  205. LOG.warning('Force exits')
  206. class DockerTask(task.Task):
  207. docker_kwargs = docker.utils.kwargs_from_env()
  208. def __init__(self):
  209. super(DockerTask, self).__init__()
  210. self._dc = None
  211. @property
  212. def dc(self):
  213. if self._dc is not None:
  214. return self._dc
  215. docker_kwargs = self.docker_kwargs.copy()
  216. self._dc = docker.APIClient(version='auto', **docker_kwargs)
  217. return self._dc
  218. class Image(object):
  219. def __init__(self, name, canonical_name, path, parent_name='',
  220. status=STATUS_UNPROCESSED, parent=None,
  221. source=None, logger=None, docker_client=None):
  222. self.name = name
  223. self.canonical_name = canonical_name
  224. self.path = path
  225. self.status = status
  226. self.parent = parent
  227. self.source = source
  228. self.parent_name = parent_name
  229. if logger is None:
  230. logger = utils.make_a_logger(image_name=name)
  231. self.logger = logger
  232. self.children = []
  233. self.plugins = []
  234. self.additions = []
  235. self.dc = docker_client
  236. def copy(self):
  237. c = Image(self.name, self.canonical_name, self.path,
  238. logger=self.logger, parent_name=self.parent_name,
  239. status=self.status, parent=self.parent)
  240. if self.source:
  241. c.source = self.source.copy()
  242. if self.children:
  243. c.children = list(self.children)
  244. if self.plugins:
  245. c.plugins = list(self.plugins)
  246. if self.additions:
  247. c.additions = list(self.additions)
  248. return c
  249. def in_docker_cache(self):
  250. return len(self.dc.images(name=self.canonical_name, quiet=True)) == 1
  251. def __repr__(self):
  252. return ("Image(%s, %s, %s, parent_name=%s,"
  253. " status=%s, parent=%s, source=%s)") % (
  254. self.name, self.canonical_name, self.path,
  255. self.parent_name, self.status, self.parent, self.source)
  256. class PushIntoQueueTask(task.Task):
  257. """Task that pushes some other task into a queue."""
  258. def __init__(self, push_task, push_queue):
  259. super(PushIntoQueueTask, self).__init__()
  260. self.push_task = push_task
  261. self.push_queue = push_queue
  262. @property
  263. def name(self):
  264. return 'PushIntoQueueTask(%s=>%s)' % (self.push_task.name,
  265. self.push_queue)
  266. def run(self):
  267. self.push_queue.put(self.push_task)
  268. self.success = True
  269. class PushTask(DockerTask):
  270. """Task that pushes an image to a docker repository."""
  271. def __init__(self, conf, image):
  272. super(PushTask, self).__init__()
  273. self.conf = conf
  274. self.image = image
  275. self.logger = image.logger
  276. @property
  277. def name(self):
  278. return 'PushTask(%s)' % self.image.name
  279. def run(self):
  280. image = self.image
  281. self.logger.info('Trying to push the image')
  282. try:
  283. self.push_image(image)
  284. except requests_exc.ConnectionError:
  285. self.logger.exception('Make sure Docker is running and that you'
  286. ' have the correct privileges to run Docker'
  287. ' (root)')
  288. image.status = STATUS_CONNECTION_ERROR
  289. except Exception:
  290. self.logger.exception('Unknown error when pushing')
  291. image.status = STATUS_PUSH_ERROR
  292. finally:
  293. if (image.status not in STATUS_ERRORS
  294. and image.status != STATUS_UNPROCESSED):
  295. self.logger.info('Pushed successfully')
  296. self.success = True
  297. else:
  298. self.success = False
  299. def push_image(self, image):
  300. kwargs = dict(stream=True, decode=True)
  301. # Since docker 3.0.0, the argument of 'insecure_registry' is removed.
  302. # To be compatible, set 'insecure_registry=True' for old releases.
  303. dc_running_ver = StrictVersion(docker.version)
  304. if dc_running_ver < StrictVersion('3.0.0'):
  305. kwargs['insecure_registry'] = True
  306. for response in self.dc.push(image.canonical_name, **kwargs):
  307. if 'stream' in response:
  308. self.logger.info(response['stream'])
  309. elif 'errorDetail' in response:
  310. image.status = STATUS_ERROR
  311. self.logger.error(response['errorDetail']['message'])
  312. class BuildTask(DockerTask):
  313. """Task that builds out an image."""
  314. def __init__(self, conf, image, push_queue):
  315. super(BuildTask, self).__init__()
  316. self.conf = conf
  317. self.image = image
  318. self.push_queue = push_queue
  319. self.nocache = not conf.cache
  320. self.forcerm = not conf.keep
  321. self.logger = image.logger
  322. @property
  323. def name(self):
  324. return 'BuildTask(%s)' % self.image.name
  325. def run(self):
  326. self.builder(self.image)
  327. if self.image.status in (STATUS_BUILT, STATUS_SKIPPED):
  328. self.success = True
  329. @property
  330. def followups(self):
  331. followups = []
  332. if self.conf.push and self.success:
  333. followups.extend([
  334. # If we are supposed to push the image into a docker
  335. # repository, then make sure we do that...
  336. PushIntoQueueTask(
  337. PushTask(self.conf, self.image),
  338. self.push_queue),
  339. ])
  340. if self.image.children and self.success:
  341. for image in self.image.children:
  342. if image.status == STATUS_UNMATCHED:
  343. continue
  344. followups.append(BuildTask(self.conf, image, self.push_queue))
  345. return followups
  346. def process_source(self, image, source):
  347. dest_archive = os.path.join(image.path, source['name'] + '-archive')
  348. if source.get('type') == 'url':
  349. self.logger.debug("Getting archive from %s", source['source'])
  350. try:
  351. r = requests.get(source['source'], timeout=self.conf.timeout)
  352. except requests_exc.Timeout:
  353. self.logger.exception(
  354. 'Request timed out while getting archive from %s',
  355. source['source'])
  356. image.status = STATUS_ERROR
  357. return
  358. if r.status_code == 200:
  359. with open(dest_archive, 'wb') as f:
  360. f.write(r.content)
  361. else:
  362. self.logger.error(
  363. 'Failed to download archive: status_code %s',
  364. r.status_code)
  365. image.status = STATUS_ERROR
  366. return
  367. elif source.get('type') == 'git':
  368. clone_dir = '{}-{}'.format(dest_archive,
  369. source['reference'].replace('/', '-'))
  370. if os.path.exists(clone_dir):
  371. self.logger.info("Clone dir %s exists. Removing it.",
  372. clone_dir)
  373. shutil.rmtree(clone_dir)
  374. try:
  375. self.logger.debug("Cloning from %s", source['source'])
  376. git.Git().clone(source['source'], clone_dir)
  377. git.Git(clone_dir).checkout(source['reference'])
  378. reference_sha = git.Git(clone_dir).rev_parse('HEAD')
  379. self.logger.debug("Git checkout by reference %s (%s)",
  380. source['reference'], reference_sha)
  381. except Exception as e:
  382. self.logger.error("Failed to get source from git", image.name)
  383. self.logger.error("Error: %s", e)
  384. # clean-up clone folder to retry
  385. shutil.rmtree(clone_dir)
  386. image.status = STATUS_ERROR
  387. return
  388. with tarfile.open(dest_archive, 'w') as tar:
  389. tar.add(clone_dir, arcname=os.path.basename(clone_dir))
  390. elif source.get('type') == 'local':
  391. self.logger.debug("Getting local archive from %s",
  392. source['source'])
  393. if os.path.isdir(source['source']):
  394. with tarfile.open(dest_archive, 'w') as tar:
  395. tar.add(source['source'],
  396. arcname=os.path.basename(source['source']))
  397. else:
  398. shutil.copyfile(source['source'], dest_archive)
  399. else:
  400. self.logger.error("Wrong source type '%s'", source.get('type'))
  401. image.status = STATUS_ERROR
  402. return
  403. # Set time on destination archive to epoch 0
  404. os.utime(dest_archive, (0, 0))
  405. return dest_archive
  406. def update_buildargs(self):
  407. buildargs = dict()
  408. if self.conf.build_args:
  409. buildargs = dict(self.conf.build_args)
  410. proxy_vars = ('HTTP_PROXY', 'http_proxy', 'HTTPS_PROXY',
  411. 'https_proxy', 'FTP_PROXY', 'ftp_proxy',
  412. 'NO_PROXY', 'no_proxy')
  413. for proxy_var in proxy_vars:
  414. if proxy_var in os.environ and proxy_var not in buildargs:
  415. buildargs[proxy_var] = os.environ.get(proxy_var)
  416. if not buildargs:
  417. return None
  418. return buildargs
  419. def builder(self, image):
  420. def make_an_archive(items, arcname, item_child_path=None):
  421. if not item_child_path:
  422. item_child_path = arcname
  423. archives = list()
  424. items_path = os.path.join(image.path, item_child_path)
  425. for item in items:
  426. archive_path = self.process_source(image, item)
  427. if image.status in STATUS_ERRORS:
  428. raise ArchivingError
  429. archives.append(archive_path)
  430. if archives:
  431. for archive in archives:
  432. with tarfile.open(archive, 'r') as archive_tar:
  433. archive_tar.extractall(path=items_path)
  434. else:
  435. try:
  436. os.mkdir(items_path)
  437. except OSError as e:
  438. if e.errno == errno.EEXIST:
  439. self.logger.info(
  440. 'Directory %s already exist. Skipping.',
  441. items_path)
  442. else:
  443. self.logger.error('Failed to create directory %s: %s',
  444. items_path, e)
  445. image.status = STATUS_CONNECTION_ERROR
  446. raise ArchivingError
  447. arc_path = os.path.join(image.path, '%s-archive' % arcname)
  448. with tarfile.open(arc_path, 'w') as tar:
  449. tar.add(items_path, arcname=arcname)
  450. return len(os.listdir(items_path))
  451. self.logger.debug('Processing')
  452. if image.status == STATUS_SKIPPED:
  453. self.logger.info('Skipping %s' % image.name)
  454. return
  455. if image.status == STATUS_UNMATCHED:
  456. return
  457. if (image.parent is not None and
  458. image.parent.status in STATUS_ERRORS):
  459. self.logger.error('Parent image error\'d with message "%s"',
  460. image.parent.status)
  461. image.status = STATUS_PARENT_ERROR
  462. return
  463. image.status = STATUS_BUILDING
  464. self.logger.info('Building')
  465. if image.source and 'source' in image.source:
  466. self.process_source(image, image.source)
  467. if image.status in STATUS_ERRORS:
  468. return
  469. if self.conf.install_type == 'source':
  470. try:
  471. plugins_am = make_an_archive(image.plugins, 'plugins')
  472. except ArchivingError:
  473. self.logger.error(
  474. "Failed turning any plugins into a plugins archive")
  475. return
  476. else:
  477. self.logger.debug(
  478. "Turned %s plugins into plugins archive",
  479. plugins_am)
  480. try:
  481. additions_am = make_an_archive(image.additions, 'additions')
  482. except ArchivingError:
  483. self.logger.error(
  484. "Failed turning any additions into a additions archive")
  485. return
  486. else:
  487. self.logger.debug(
  488. "Turned %s additions into additions archive",
  489. additions_am)
  490. # Pull the latest image for the base distro only
  491. pull = self.conf.pull if image.parent is None else False
  492. buildargs = self.update_buildargs()
  493. try:
  494. for stream in self.dc.build(path=image.path,
  495. tag=image.canonical_name,
  496. nocache=not self.conf.cache,
  497. rm=True,
  498. decode=True,
  499. network_mode=self.conf.network_mode,
  500. pull=pull,
  501. forcerm=self.forcerm,
  502. buildargs=buildargs):
  503. if 'stream' in stream:
  504. for line in stream['stream'].split('\n'):
  505. if line:
  506. self.logger.info('%s', line)
  507. if 'errorDetail' in stream:
  508. image.status = STATUS_ERROR
  509. self.logger.error('Error\'d with the following message')
  510. for line in stream['errorDetail']['message'].split('\n'):
  511. if line:
  512. self.logger.error('%s', line)
  513. return
  514. if image.status != STATUS_ERROR and self.conf.squash:
  515. self.squash()
  516. except docker.errors.DockerException:
  517. image.status = STATUS_ERROR
  518. self.logger.exception('Unknown docker error when building')
  519. except Exception:
  520. image.status = STATUS_ERROR
  521. self.logger.exception('Unknown error when building')
  522. else:
  523. image.status = STATUS_BUILT
  524. self.logger.info('Built')
  525. def squash(self):
  526. image_tag = self.image.canonical_name
  527. image_id = self.dc.inspect_image(image_tag)['Id']
  528. parent_history = self.dc.history(self.image.parent_name)
  529. parent_last_layer = parent_history[0]['Id']
  530. self.logger.info('Parent lastest layer is: %s' % parent_last_layer)
  531. utils.squash(image_id, image_tag, from_layer=parent_last_layer,
  532. cleanup=self.conf.squash_cleanup,
  533. tmp_dir=self.conf.squash_tmp_dir)
  534. self.logger.info('Image is squashed successfully')
  535. class WorkerThread(threading.Thread):
  536. """Thread that executes tasks until the queue provides a tombstone."""
  537. #: Object to be put on worker queues to get them to die.
  538. tombstone = object()
  539. def __init__(self, conf, queue):
  540. super(WorkerThread, self).__init__()
  541. self.queue = queue
  542. self.conf = conf
  543. self.should_stop = False
  544. def run(self):
  545. while not self.should_stop:
  546. task = self.queue.get()
  547. if task is self.tombstone:
  548. # Ensure any other threads also get the tombstone.
  549. self.queue.put(task)
  550. break
  551. try:
  552. for attempt in six.moves.range(self.conf.retries + 1):
  553. if self.should_stop:
  554. break
  555. LOG.info("Attempt number: %s to run task: %s ",
  556. attempt + 1, task.name)
  557. try:
  558. task.run()
  559. if task.success:
  560. break
  561. except Exception:
  562. LOG.exception('Unhandled error when running %s',
  563. task.name)
  564. # try again...
  565. task.reset()
  566. if task.success and not self.should_stop:
  567. for next_task in task.followups:
  568. LOG.info('Added next task %s to queue',
  569. next_task.name)
  570. self.queue.put(next_task)
  571. finally:
  572. self.queue.task_done()
  573. class KollaWorker(object):
  574. def __init__(self, conf):
  575. self.conf = conf
  576. self.images_dir = self._get_images_dir()
  577. self.registry = conf.registry
  578. if self.registry:
  579. self.namespace = self.registry + '/' + conf.namespace
  580. else:
  581. self.namespace = conf.namespace
  582. self.base = conf.base
  583. self.base_tag = conf.base_tag
  584. self.install_type = conf.install_type
  585. self.tag = conf.tag
  586. self.base_arch = conf.base_arch
  587. self.images = list()
  588. rpm_setup_config = ([repo_file for repo_file in
  589. conf.rpm_setup_config if repo_file is not None])
  590. self.rpm_setup = self.build_rpm_setup(rpm_setup_config)
  591. rh_base = ['centos', 'oraclelinux', 'rhel']
  592. rh_type = ['source', 'binary', 'rdo', 'rhos']
  593. deb_base = ['ubuntu', 'debian']
  594. deb_type = ['source', 'binary']
  595. if not ((self.base in rh_base and self.install_type in rh_type) or
  596. (self.base in deb_base and self.install_type in deb_type)):
  597. raise exception.KollaMismatchBaseTypeException(
  598. '{} is unavailable for {}'.format(self.install_type, self.base)
  599. )
  600. if self.install_type == 'binary':
  601. self.install_metatype = 'rdo'
  602. elif self.install_type == 'source':
  603. self.install_metatype = 'mixed'
  604. elif self.install_type == 'rdo':
  605. self.install_type = 'binary'
  606. self.install_metatype = 'rdo'
  607. elif self.install_type == 'rhos':
  608. self.install_type = 'binary'
  609. self.install_metatype = 'rhos'
  610. else:
  611. raise exception.KollaUnknownBuildTypeException(
  612. 'Unknown install type'
  613. )
  614. self.image_prefix = self.base + '-' + self.install_type + '-'
  615. self.regex = conf.regex
  616. self.image_statuses_bad = dict()
  617. self.image_statuses_good = dict()
  618. self.image_statuses_unmatched = dict()
  619. self.image_statuses_skipped = dict()
  620. self.maintainer = conf.maintainer
  621. docker_kwargs = docker.utils.kwargs_from_env()
  622. try:
  623. self.dc = docker.APIClient(version='auto', **docker_kwargs)
  624. except docker.errors.DockerException as e:
  625. self.dc = None
  626. if not conf.template_only:
  627. raise e
  628. def _get_images_dir(self):
  629. possible_paths = (
  630. PROJECT_ROOT,
  631. os.path.join(sys.prefix, 'share/kolla'),
  632. os.path.join(sys.prefix, 'local/share/kolla'),
  633. # NOTE(zioproto): When Kolla is used within a snap, the env var
  634. # $SNAP is the directory where the snap is mounted.
  635. # https://github.com/zioproto/snap-kolla
  636. # More info in snap packages https://snapcraft.io
  637. os.path.join(os.environ.get('SNAP', ''), 'share/kolla'))
  638. for path in possible_paths:
  639. image_path = os.path.join(path, 'docker')
  640. # NOTE(SamYaple): We explicitly check for the base folder to ensure
  641. # this is the correct path
  642. # TODO(SamYaple): Improve this to make this safer
  643. if os.path.exists(os.path.join(image_path, 'base')):
  644. LOG.info('Found the docker image folder at %s', image_path)
  645. return image_path
  646. else:
  647. raise exception.KollaDirNotFoundException('Image dir can not '
  648. 'be found')
  649. def build_rpm_setup(self, rpm_setup_config):
  650. """Generates a list of docker commands based on provided configuration.
  651. :param rpm_setup_config: A list of .rpm or .repo paths or URLs
  652. (can be empty)
  653. :return: A list of docker commands
  654. """
  655. rpm_setup = list()
  656. for config in rpm_setup_config:
  657. if config.endswith('.rpm'):
  658. # RPM files can be installed with yum from file path or url
  659. cmd = "RUN yum -y install {}".format(config)
  660. elif config.endswith('.repo'):
  661. if config.startswith('http'):
  662. # Curl http://url/etc.repo to /etc/yum.repos.d/etc.repo
  663. name = config.split('/')[-1]
  664. cmd = "RUN curl -L {} -o /etc/yum.repos.d/{}".format(
  665. config, name)
  666. else:
  667. # Copy .repo file from filesystem
  668. cmd = "COPY {} /etc/yum.repos.d/".format(config)
  669. elif not config:
  670. cmd = ''
  671. else:
  672. raise exception.KollaRpmSetupUnknownConfig(
  673. 'RPM setup must be provided as .rpm or .repo files.'
  674. ' Attempted configuration was {}'.format(config)
  675. )
  676. rpm_setup.append(cmd)
  677. return rpm_setup
  678. def copy_apt_files(self):
  679. if self.conf.apt_sources_list:
  680. shutil.copyfile(
  681. self.conf.apt_sources_list,
  682. os.path.join(self.working_dir, "base", "sources.list")
  683. )
  684. if self.conf.apt_preferences:
  685. shutil.copyfile(
  686. self.conf.apt_preferences,
  687. os.path.join(self.working_dir, "base", "apt_preferences")
  688. )
  689. def copy_dir(self, src, dest):
  690. if not os.path.isdir(dest):
  691. shutil.copytree(src, dest)
  692. else:
  693. for file in os.listdir(src):
  694. src_path = os.path.join(src, file)
  695. dest_path = os.path.join(dest, file)
  696. if os.path.isdir(src_path):
  697. self.copy_dir(src_path, dest_path)
  698. else:
  699. shutil.copy2(src_path, dest_path)
  700. def setup_working_dir(self):
  701. """Creates a working directory for use while building."""
  702. if self.conf.work_dir:
  703. self.working_dir = os.path.join(self.conf.work_dir, 'docker')
  704. else:
  705. ts = time.time()
  706. ts = datetime.datetime.fromtimestamp(ts).strftime(
  707. '%Y-%m-%d_%H-%M-%S_')
  708. self.temp_dir = tempfile.mkdtemp(prefix='kolla-' + ts)
  709. self.working_dir = os.path.join(self.temp_dir, 'docker')
  710. self.copy_dir(self.images_dir, self.working_dir)
  711. for dir in self.conf.docker_dir:
  712. self.copy_dir(dir, self.working_dir)
  713. self.copy_apt_files()
  714. LOG.debug('Created working dir: %s', self.working_dir)
  715. def set_time(self):
  716. for root, dirs, files in os.walk(self.working_dir):
  717. for file_ in files:
  718. os.utime(os.path.join(root, file_), (0, 0))
  719. for dir_ in dirs:
  720. os.utime(os.path.join(root, dir_), (0, 0))
  721. LOG.debug('Set atime and mtime to 0 for all content in working dir')
  722. def _get_filters(self):
  723. filters = {
  724. 'customizable': jinja_filters.customizable,
  725. }
  726. return filters
  727. def _get_methods(self):
  728. """Mapping of available Jinja methods.
  729. return a dictionary that maps available function names and their
  730. corresponding python methods to make them available in jinja templates
  731. """
  732. return {
  733. 'debian_package_install': jinja_methods.debian_package_install,
  734. }
  735. def get_users(self):
  736. all_sections = (set(six.iterkeys(self.conf._groups)) |
  737. set(self.conf.list_all_sections()))
  738. ret = dict()
  739. for section in all_sections:
  740. match = re.search('^.*-user$', section)
  741. if match:
  742. user = self.conf[match.group(0)]
  743. ret[match.group(0)[:-5]] = {
  744. 'uid': user.uid,
  745. 'gid': user.gid,
  746. }
  747. return ret
  748. def create_dockerfiles(self):
  749. kolla_version = version.version_info.cached_version_string()
  750. supported_distro_release = common_config.DISTRO_RELEASE.get(
  751. self.base)
  752. for path in self.docker_build_paths:
  753. template_name = "Dockerfile.j2"
  754. image_name = path.split("/")[-1]
  755. ts = time.time()
  756. build_date = datetime.datetime.fromtimestamp(ts).strftime(
  757. '%Y%m%d')
  758. values = {'base_distro': self.base,
  759. 'base_image': self.conf.base_image,
  760. 'base_distro_tag': self.base_tag,
  761. 'base_arch': self.base_arch,
  762. 'supported_distro_release': supported_distro_release,
  763. 'install_metatype': self.install_metatype,
  764. 'image_prefix': self.image_prefix,
  765. 'install_type': self.install_type,
  766. 'namespace': self.namespace,
  767. 'tag': self.tag,
  768. 'maintainer': self.maintainer,
  769. 'kolla_version': kolla_version,
  770. 'image_name': image_name,
  771. 'users': self.get_users(),
  772. 'rpm_setup': self.rpm_setup,
  773. 'build_date': build_date}
  774. env = jinja2.Environment( # nosec: not used to render HTML
  775. loader=jinja2.FileSystemLoader(self.working_dir))
  776. env.filters.update(self._get_filters())
  777. env.globals.update(self._get_methods())
  778. tpl_path = os.path.join(
  779. os.path.relpath(path, self.working_dir),
  780. template_name)
  781. template = env.get_template(tpl_path)
  782. if self.conf.template_override:
  783. tpl_dict = self._merge_overrides(self.conf.template_override)
  784. template_name = os.path.basename(list(tpl_dict.keys())[0])
  785. values['parent_template'] = template
  786. env = jinja2.Environment( # nosec: not used to render HTML
  787. loader=jinja2.DictLoader(tpl_dict))
  788. env.filters.update(self._get_filters())
  789. env.globals.update(self._get_methods())
  790. template = env.get_template(template_name)
  791. content = template.render(values, env=os.environ)
  792. content_path = os.path.join(path, 'Dockerfile')
  793. with open(content_path, 'w') as f:
  794. LOG.debug("Rendered %s into:", tpl_path)
  795. LOG.debug(content)
  796. f.write(content)
  797. LOG.debug("Wrote it to %s", content_path)
  798. def _merge_overrides(self, overrides):
  799. tpl_name = os.path.basename(overrides[0])
  800. with open(overrides[0], 'r') as f:
  801. tpl_content = f.read()
  802. for override in overrides[1:]:
  803. with open(override, 'r') as f:
  804. cont = f.read()
  805. # Remove extends header
  806. cont = re.sub(r'.*\{\%.*extends.*\n', '', cont)
  807. tpl_content += cont
  808. return {tpl_name: tpl_content}
  809. def find_dockerfiles(self):
  810. """Recursive search for Dockerfiles in the working directory."""
  811. self.docker_build_paths = list()
  812. path = self.working_dir
  813. filename = 'Dockerfile.j2'
  814. for root, dirs, names in os.walk(path):
  815. if filename in names:
  816. self.docker_build_paths.append(root)
  817. LOG.debug('Found %s', root.split(self.working_dir)[1])
  818. LOG.debug('Found %d Dockerfiles', len(self.docker_build_paths))
  819. def cleanup(self):
  820. """Remove temp files."""
  821. if not self.conf.work_dir:
  822. shutil.rmtree(self.temp_dir)
  823. def filter_images(self):
  824. """Filter which images to build."""
  825. filter_ = list()
  826. if self.regex:
  827. filter_ += self.regex
  828. elif self.conf.profile:
  829. for profile in self.conf.profile:
  830. if profile not in self.conf.profiles:
  831. self.conf.register_opt(cfg.ListOpt(profile,
  832. default=[]),
  833. 'profiles')
  834. if len(self.conf.profiles[profile]) == 0:
  835. msg = 'Profile: {} does not exist'.format(profile)
  836. raise ValueError(msg)
  837. else:
  838. filter_ += self.conf.profiles[profile]
  839. if filter_:
  840. patterns = re.compile(r"|".join(filter_).join('()'))
  841. for image in self.images:
  842. if image.status in (STATUS_MATCHED, STATUS_SKIPPED):
  843. continue
  844. if re.search(patterns, image.name):
  845. image.status = STATUS_MATCHED
  846. while (image.parent is not None and
  847. image.parent.status not in (STATUS_MATCHED,
  848. STATUS_SKIPPED)):
  849. image = image.parent
  850. if self.conf.skip_parents:
  851. image.status = STATUS_SKIPPED
  852. elif (self.conf.skip_existing and
  853. image.in_docker_cache()):
  854. image.status = STATUS_SKIPPED
  855. else:
  856. image.status = STATUS_MATCHED
  857. LOG.debug('Image %s matched regex', image.name)
  858. else:
  859. image.status = STATUS_UNMATCHED
  860. else:
  861. for image in self.images:
  862. image.status = STATUS_MATCHED
  863. skipped_images = SKIPPED_IMAGES.get('%s+%s' % (self.base,
  864. self.install_type))
  865. for image in self.images:
  866. if image.name in skipped_images:
  867. image.status = STATUS_UNMATCHED
  868. def summary(self):
  869. """Walk the dictionary of images statuses and print results."""
  870. # For debug we print the logs again if the image error'd. This is to
  871. # help us debug and it will be extra helpful in the gate.
  872. for image in self.images:
  873. if image.status in STATUS_ERRORS:
  874. LOG.debug("Image %s failed", image.name)
  875. self.get_image_statuses()
  876. results = {
  877. 'built': [],
  878. 'failed': [],
  879. 'not_matched': [],
  880. 'skipped': [],
  881. }
  882. if self.image_statuses_good:
  883. LOG.info("=========================")
  884. LOG.info("Successfully built images")
  885. LOG.info("=========================")
  886. for name in sorted(self.image_statuses_good.keys()):
  887. LOG.info(name)
  888. results['built'].append({
  889. 'name': name,
  890. })
  891. if self.image_statuses_bad:
  892. LOG.info("===========================")
  893. LOG.info("Images that failed to build")
  894. LOG.info("===========================")
  895. for name, status in sorted(self.image_statuses_bad.items()):
  896. LOG.error('%s Failed with status: %s', name, status)
  897. results['failed'].append({
  898. 'name': name,
  899. 'status': status,
  900. })
  901. if self.conf.logs_dir and status == STATUS_ERROR:
  902. os.symlink("%s.log" % name,
  903. os.path.join(self.conf.logs_dir,
  904. "000_FAILED_%s.log" % name))
  905. if self.image_statuses_unmatched:
  906. LOG.debug("=====================================")
  907. LOG.debug("Images not matched for build by regex")
  908. LOG.debug("=====================================")
  909. for name in sorted(self.image_statuses_unmatched.keys()):
  910. LOG.debug(name)
  911. results['not_matched'].append({
  912. 'name': name,
  913. })
  914. if self.image_statuses_skipped:
  915. LOG.debug("================================")
  916. LOG.debug("Images skipped due build options")
  917. LOG.debug("================================")
  918. for name in sorted(self.image_statuses_skipped.keys()):
  919. LOG.debug(name)
  920. results['skipped'].append({
  921. 'name': name,
  922. })
  923. return results
  924. def get_image_statuses(self):
  925. if any([self.image_statuses_bad,
  926. self.image_statuses_good,
  927. self.image_statuses_unmatched,
  928. self.image_statuses_skipped]):
  929. return (self.image_statuses_bad,
  930. self.image_statuses_good,
  931. self.image_statuses_unmatched,
  932. self.image_statuses_skipped)
  933. for image in self.images:
  934. if image.status == STATUS_BUILT:
  935. self.image_statuses_good[image.name] = image.status
  936. elif image.status == STATUS_UNMATCHED:
  937. self.image_statuses_unmatched[image.name] = image.status
  938. elif image.status == STATUS_SKIPPED:
  939. self.image_statuses_skipped[image.name] = image.status
  940. else:
  941. self.image_statuses_bad[image.name] = image.status
  942. return (self.image_statuses_bad,
  943. self.image_statuses_good,
  944. self.image_statuses_unmatched,
  945. self.image_statuses_skipped)
  946. def build_image_list(self):
  947. def process_source_installation(image, section):
  948. installation = dict()
  949. # NOTE(jeffrey4l): source is not needed when the type is None
  950. if self.conf._get('type', self.conf._get_group(section)) is None:
  951. if image.parent_name is None:
  952. LOG.debug('No source location found in section %s',
  953. section)
  954. else:
  955. installation['type'] = self.conf[section]['type']
  956. installation['source'] = self.conf[section]['location']
  957. installation['name'] = section
  958. if installation['type'] == 'git':
  959. installation['reference'] = self.conf[section]['reference']
  960. return installation
  961. all_sections = (set(six.iterkeys(self.conf._groups)) |
  962. set(self.conf.list_all_sections()))
  963. for path in self.docker_build_paths:
  964. # Reading parent image name
  965. with open(os.path.join(path, 'Dockerfile')) as f:
  966. content = f.read()
  967. image_name = os.path.basename(path)
  968. canonical_name = (self.namespace + '/' + self.image_prefix +
  969. image_name + ':' + self.tag)
  970. parent_search_pattern = re.compile(r'^FROM.*$', re.MULTILINE)
  971. match = re.search(parent_search_pattern, content)
  972. if match:
  973. parent_name = match.group(0).split(' ')[1]
  974. else:
  975. parent_name = ''
  976. del match
  977. image = Image(image_name, canonical_name, path,
  978. parent_name=parent_name,
  979. logger=utils.make_a_logger(self.conf, image_name),
  980. docker_client=self.dc)
  981. if self.install_type == 'source':
  982. # NOTE(jeffrey4l): register the opts if the section didn't
  983. # register in the kolla/common/config.py file
  984. if image.name not in self.conf._groups:
  985. self.conf.register_opts(common_config.get_source_opts(),
  986. image.name)
  987. image.source = process_source_installation(image, image.name)
  988. for plugin in [match.group(0) for match in
  989. (re.search('^{}-plugin-.+'.format(image.name),
  990. section) for section in
  991. all_sections) if match]:
  992. try:
  993. self.conf.register_opts(
  994. common_config.get_source_opts(),
  995. plugin
  996. )
  997. except cfg.DuplicateOptError:
  998. LOG.debug('Plugin %s already registered in config',
  999. plugin)
  1000. image.plugins.append(
  1001. process_source_installation(image, plugin))
  1002. for addition in [
  1003. match.group(0) for match in
  1004. (re.search('^{}-additions-.+'.format(image.name),
  1005. section) for section in all_sections) if match]:
  1006. try:
  1007. self.conf.register_opts(
  1008. common_config.get_source_opts(),
  1009. addition
  1010. )
  1011. except cfg.DuplicateOptError:
  1012. LOG.debug('Addition %s already registered in config',
  1013. addition)
  1014. image.additions.append(
  1015. process_source_installation(image, addition))
  1016. self.images.append(image)
  1017. def save_dependency(self, to_file):
  1018. try:
  1019. import graphviz
  1020. except ImportError:
  1021. LOG.error('"graphviz" is required for save dependency')
  1022. raise
  1023. dot = graphviz.Digraph(comment='Docker Images Dependency')
  1024. dot.body.extend(['rankdir=LR'])
  1025. for image in self.images:
  1026. if image.status not in [STATUS_MATCHED]:
  1027. continue
  1028. dot.node(image.name)
  1029. if image.parent is not None:
  1030. dot.edge(image.parent.name, image.name)
  1031. with open(to_file, 'w') as f:
  1032. f.write(dot.source)
  1033. def list_images(self):
  1034. for count, image in enumerate([
  1035. image for image in self.images if image.status == STATUS_MATCHED
  1036. ]):
  1037. print(count + 1, ':', image.name)
  1038. def list_dependencies(self):
  1039. match = False
  1040. for image in self.images:
  1041. if image.status in [STATUS_MATCHED]:
  1042. match = True
  1043. if image.parent is None:
  1044. base = image
  1045. if not match:
  1046. print('Nothing matched!')
  1047. return
  1048. def list_children(images, ancestry):
  1049. children = six.next(iter(ancestry.values()))
  1050. for image in images:
  1051. if image.status not in [STATUS_MATCHED]:
  1052. continue
  1053. if not image.children:
  1054. children.append(image.name)
  1055. else:
  1056. newparent = {image.name: []}
  1057. children.append(newparent)
  1058. list_children(image.children, newparent)
  1059. ancestry = {base.name: []}
  1060. list_children(base.children, ancestry)
  1061. json.dump(ancestry, sys.stdout, indent=2)
  1062. def find_parents(self):
  1063. """Associate all images with parents and children."""
  1064. sort_images = dict()
  1065. for image in self.images:
  1066. sort_images[image.canonical_name] = image
  1067. for parent_name, parent in sort_images.items():
  1068. for image in sort_images.values():
  1069. if image.parent_name == parent_name:
  1070. parent.children.append(image)
  1071. image.parent = parent
  1072. def build_queue(self, push_queue):
  1073. """Organizes Queue list.
  1074. Return a list of Queues that have been organized into a hierarchy
  1075. based on dependencies
  1076. """
  1077. self.build_image_list()
  1078. self.find_parents()
  1079. self.filter_images()
  1080. queue = six.moves.queue.Queue()
  1081. for image in self.images:
  1082. if image.status in (STATUS_UNMATCHED, STATUS_SKIPPED):
  1083. # Don't bother queuing up build tasks for things that
  1084. # were not matched in the first place... (not worth the
  1085. # effort to run them, if they won't be used anyway).
  1086. continue
  1087. if image.parent is None:
  1088. queue.put(BuildTask(self.conf, image, push_queue))
  1089. LOG.info('Added image %s to queue', image.name)
  1090. return queue
  1091. def run_build():
  1092. """Build container images.
  1093. :return: A 4-tuple containing bad, good, unmatched and skipped container
  1094. image status dicts, or None if no images were built.
  1095. """
  1096. conf = cfg.ConfigOpts()
  1097. common_config.parse(conf, sys.argv[1:], prog='kolla-build')
  1098. if conf.debug:
  1099. LOG.setLevel(logging.DEBUG)
  1100. if conf.squash:
  1101. squash_version = utils.get_docker_squash_version()
  1102. LOG.info('Image squash is enabled and "docker-squash" version is %s',
  1103. squash_version)
  1104. kolla = KollaWorker(conf)
  1105. kolla.setup_working_dir()
  1106. kolla.find_dockerfiles()
  1107. kolla.create_dockerfiles()
  1108. if conf.template_only:
  1109. LOG.info('Dockerfiles are generated in %s', kolla.working_dir)
  1110. return
  1111. # We set the atime and mtime to 0 epoch to preserve allow the Docker cache
  1112. # to work like we want. A different size or hash will still force a rebuild
  1113. kolla.set_time()
  1114. if conf.save_dependency:
  1115. kolla.build_image_list()
  1116. kolla.find_parents()
  1117. kolla.filter_images()
  1118. kolla.save_dependency(conf.save_dependency)
  1119. LOG.info('Docker images dependency are saved in %s',
  1120. conf.save_dependency)
  1121. return
  1122. if conf.list_images:
  1123. kolla.build_image_list()
  1124. kolla.find_parents()
  1125. kolla.filter_images()
  1126. kolla.list_images()
  1127. return
  1128. if conf.list_dependencies:
  1129. kolla.build_image_list()
  1130. kolla.find_parents()
  1131. kolla.filter_images()
  1132. kolla.list_dependencies()
  1133. return
  1134. push_queue = six.moves.queue.Queue()
  1135. queue = kolla.build_queue(push_queue)
  1136. workers = []
  1137. with join_many(workers):
  1138. try:
  1139. for x in six.moves.range(conf.threads):
  1140. worker = WorkerThread(conf, queue)
  1141. worker.setDaemon(True)
  1142. worker.start()
  1143. workers.append(worker)
  1144. for x in six.moves.range(conf.push_threads):
  1145. worker = WorkerThread(conf, push_queue)
  1146. worker.setDaemon(True)
  1147. worker.start()
  1148. workers.append(worker)
  1149. # sleep until queue is empty
  1150. while queue.unfinished_tasks or push_queue.unfinished_tasks:
  1151. time.sleep(3)
  1152. # ensure all threads exited happily
  1153. push_queue.put(WorkerThread.tombstone)
  1154. queue.put(WorkerThread.tombstone)
  1155. except KeyboardInterrupt:
  1156. for w in workers:
  1157. w.should_stop = True
  1158. push_queue.put(WorkerThread.tombstone)
  1159. queue.put(WorkerThread.tombstone)
  1160. raise
  1161. results = kolla.summary()
  1162. kolla.cleanup()
  1163. if conf.format == 'json':
  1164. print(json.dumps(results))
  1165. return kolla.get_image_statuses()