openshift_facts.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  1. #!/usr/bin/python
  2. # pylint: disable=too-many-lines
  3. # -*- coding: utf-8 -*-
  4. # vim: expandtab:tabstop=4:shiftwidth=4
  5. # Reason: Disable pylint too-many-lines because we don't want to split up this file.
  6. # Status: Permanently disabled to keep this module as self-contained as possible.
  7. """Ansible module for retrieving and setting openshift related facts"""
  8. DOCUMENTATION = '''
  9. ---
  10. module: openshift_facts
  11. short_description: Cluster Facts
  12. author: Jason DeTiberus
  13. requirements: [ ]
  14. '''
  15. EXAMPLES = '''
  16. '''
  17. import ConfigParser
  18. import copy
  19. import io
  20. import os
  21. import yaml
  22. from distutils.util import strtobool
  23. from distutils.version import LooseVersion
  24. import struct
  25. import socket
  26. from dbus import SystemBus, Interface
  27. from dbus.exceptions import DBusException
  28. def migrate_docker_facts(facts):
  29. """ Apply migrations for docker facts """
  30. params = {
  31. 'common': (
  32. 'additional_registries',
  33. 'insecure_registries',
  34. 'blocked_registries',
  35. 'options'
  36. ),
  37. 'node': (
  38. 'log_driver',
  39. 'log_options'
  40. )
  41. }
  42. if 'docker' not in facts:
  43. facts['docker'] = {}
  44. for role in params.keys():
  45. if role in facts:
  46. for param in params[role]:
  47. old_param = 'docker_' + param
  48. if old_param in facts[role]:
  49. facts['docker'][param] = facts[role].pop(old_param)
  50. if 'node' in facts and 'portal_net' in facts['node']:
  51. facts['docker']['hosted_registry_insecure'] = True
  52. facts['docker']['hosted_registry_network'] = facts['node'].pop('portal_net')
  53. # log_options was originally meant to be a comma separated string, but
  54. # we now prefer an actual list, with backward compatability:
  55. if 'log_options' in facts['docker'] and \
  56. isinstance(facts['docker']['log_options'], basestring):
  57. facts['docker']['log_options'] = facts['docker']['log_options'].split(",")
  58. return facts
  59. # TODO: We should add a generic migration function that takes source and destination
  60. # paths and does the right thing rather than one function for common, one for node, etc.
  61. def migrate_common_facts(facts):
  62. """ Migrate facts from various roles into common """
  63. params = {
  64. 'node': ('portal_net'),
  65. 'master': ('portal_net')
  66. }
  67. if 'common' not in facts:
  68. facts['common'] = {}
  69. for role in params.keys():
  70. if role in facts:
  71. for param in params[role]:
  72. if param in facts[role]:
  73. facts['common'][param] = facts[role].pop(param)
  74. return facts
  75. def migrate_node_facts(facts):
  76. """ Migrate facts from various roles into node """
  77. params = {
  78. 'common': ('dns_ip'),
  79. }
  80. if 'node' not in facts:
  81. facts['node'] = {}
  82. for role in params.keys():
  83. if role in facts:
  84. for param in params[role]:
  85. if param in facts[role]:
  86. facts['node'][param] = facts[role].pop(param)
  87. return facts
  88. def migrate_local_facts(facts):
  89. """ Apply migrations of local facts """
  90. migrated_facts = copy.deepcopy(facts)
  91. migrated_facts = migrate_docker_facts(migrated_facts)
  92. migrated_facts = migrate_common_facts(migrated_facts)
  93. migrated_facts = migrate_node_facts(migrated_facts)
  94. migrated_facts = migrate_hosted_facts(migrated_facts)
  95. return migrated_facts
  96. def migrate_hosted_facts(facts):
  97. """ Apply migrations for master facts """
  98. if 'master' in facts:
  99. if 'router_selector' in facts['master']:
  100. if 'hosted' not in facts:
  101. facts['hosted'] = {}
  102. if 'router' not in facts['hosted']:
  103. facts['hosted']['router'] = {}
  104. facts['hosted']['router']['selector'] = facts['master'].pop('router_selector')
  105. return facts
  106. def first_ip(network):
  107. """ Return the first IPv4 address in network
  108. Args:
  109. network (str): network in CIDR format
  110. Returns:
  111. str: first IPv4 address
  112. """
  113. atoi = lambda addr: struct.unpack("!I", socket.inet_aton(addr))[0]
  114. itoa = lambda addr: socket.inet_ntoa(struct.pack("!I", addr))
  115. (address, netmask) = network.split('/')
  116. netmask_i = (0xffffffff << (32 - atoi(netmask))) & 0xffffffff
  117. return itoa((atoi(address) & netmask_i) + 1)
  118. def hostname_valid(hostname):
  119. """ Test if specified hostname should be considered valid
  120. Args:
  121. hostname (str): hostname to test
  122. Returns:
  123. bool: True if valid, otherwise False
  124. """
  125. if (not hostname or
  126. hostname.startswith('localhost') or
  127. hostname.endswith('localdomain') or
  128. len(hostname.split('.')) < 2):
  129. return False
  130. return True
  131. def choose_hostname(hostnames=None, fallback=''):
  132. """ Choose a hostname from the provided hostnames
  133. Given a list of hostnames and a fallback value, choose a hostname to
  134. use. This function will prefer fqdns if they exist (excluding any that
  135. begin with localhost or end with localdomain) over ip addresses.
  136. Args:
  137. hostnames (list): list of hostnames
  138. fallback (str): default value to set if hostnames does not contain
  139. a valid hostname
  140. Returns:
  141. str: chosen hostname
  142. """
  143. hostname = fallback
  144. if hostnames is None:
  145. return hostname
  146. ip_regex = r'\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z'
  147. ips = [i for i in hostnames
  148. if (i is not None and isinstance(i, basestring)
  149. and re.match(ip_regex, i))]
  150. hosts = [i for i in hostnames
  151. if i is not None and i != '' and i not in ips]
  152. for host_list in (hosts, ips):
  153. for host in host_list:
  154. if hostname_valid(host):
  155. return host
  156. return hostname
  157. def query_metadata(metadata_url, headers=None, expect_json=False):
  158. """ Return metadata from the provided metadata_url
  159. Args:
  160. metadata_url (str): metadata url
  161. headers (dict): headers to set for metadata request
  162. expect_json (bool): does the metadata_url return json
  163. Returns:
  164. dict or list: metadata request result
  165. """
  166. result, info = fetch_url(module, metadata_url, headers=headers)
  167. if info['status'] != 200:
  168. raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
  169. if expect_json:
  170. return module.from_json(result.read())
  171. else:
  172. return [line.strip() for line in result.readlines()]
  173. def walk_metadata(metadata_url, headers=None, expect_json=False):
  174. """ Walk the metadata tree and return a dictionary of the entire tree
  175. Args:
  176. metadata_url (str): metadata url
  177. headers (dict): headers to set for metadata request
  178. expect_json (bool): does the metadata_url return json
  179. Returns:
  180. dict: the result of walking the metadata tree
  181. """
  182. metadata = dict()
  183. for line in query_metadata(metadata_url, headers, expect_json):
  184. if line.endswith('/') and not line == 'public-keys/':
  185. key = line[:-1]
  186. metadata[key] = walk_metadata(metadata_url + line,
  187. headers, expect_json)
  188. else:
  189. results = query_metadata(metadata_url + line, headers,
  190. expect_json)
  191. if len(results) == 1:
  192. # disable pylint maybe-no-member because overloaded use of
  193. # the module name causes pylint to not detect that results
  194. # is an array or hash
  195. # pylint: disable=maybe-no-member
  196. metadata[line] = results.pop()
  197. else:
  198. metadata[line] = results
  199. return metadata
  200. def get_provider_metadata(metadata_url, supports_recursive=False,
  201. headers=None, expect_json=False):
  202. """ Retrieve the provider metadata
  203. Args:
  204. metadata_url (str): metadata url
  205. supports_recursive (bool): does the provider metadata api support
  206. recursion
  207. headers (dict): headers to set for metadata request
  208. expect_json (bool): does the metadata_url return json
  209. Returns:
  210. dict: the provider metadata
  211. """
  212. try:
  213. if supports_recursive:
  214. metadata = query_metadata(metadata_url, headers,
  215. expect_json)
  216. else:
  217. metadata = walk_metadata(metadata_url, headers,
  218. expect_json)
  219. except OpenShiftFactsMetadataUnavailableError:
  220. metadata = None
  221. return metadata
  222. def normalize_gce_facts(metadata, facts):
  223. """ Normalize gce facts
  224. Args:
  225. metadata (dict): provider metadata
  226. facts (dict): facts to update
  227. Returns:
  228. dict: the result of adding the normalized metadata to the provided
  229. facts dict
  230. """
  231. for interface in metadata['instance']['networkInterfaces']:
  232. int_info = dict(ips=[interface['ip']], network_type='gce')
  233. int_info['public_ips'] = [ac['externalIp'] for ac
  234. in interface['accessConfigs']]
  235. int_info['public_ips'].extend(interface['forwardedIps'])
  236. _, _, network_id = interface['network'].rpartition('/')
  237. int_info['network_id'] = network_id
  238. facts['network']['interfaces'].append(int_info)
  239. _, _, zone = metadata['instance']['zone'].rpartition('/')
  240. facts['zone'] = zone
  241. # GCE currently only supports a single interface
  242. facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
  243. pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
  244. facts['network']['public_ip'] = pub_ip
  245. facts['network']['hostname'] = metadata['instance']['hostname']
  246. # TODO: attempt to resolve public_hostname
  247. facts['network']['public_hostname'] = facts['network']['public_ip']
  248. return facts
  249. def normalize_aws_facts(metadata, facts):
  250. """ Normalize aws facts
  251. Args:
  252. metadata (dict): provider metadata
  253. facts (dict): facts to update
  254. Returns:
  255. dict: the result of adding the normalized metadata to the provided
  256. facts dict
  257. """
  258. for interface in sorted(
  259. metadata['network']['interfaces']['macs'].values(),
  260. key=lambda x: x['device-number']
  261. ):
  262. int_info = dict()
  263. var_map = {'ips': 'local-ipv4s', 'public_ips': 'public-ipv4s'}
  264. for ips_var, int_var in var_map.iteritems():
  265. ips = interface.get(int_var)
  266. if isinstance(ips, basestring):
  267. int_info[ips_var] = [ips]
  268. else:
  269. int_info[ips_var] = ips
  270. if 'vpc-id' in interface:
  271. int_info['network_type'] = 'vpc'
  272. else:
  273. int_info['network_type'] = 'classic'
  274. if int_info['network_type'] == 'vpc':
  275. int_info['network_id'] = interface['subnet-id']
  276. else:
  277. int_info['network_id'] = None
  278. facts['network']['interfaces'].append(int_info)
  279. facts['zone'] = metadata['placement']['availability-zone']
  280. # TODO: actually attempt to determine default local and public ips
  281. # by using the ansible default ip fact and the ipv4-associations
  282. # from the ec2 metadata
  283. facts['network']['ip'] = metadata.get('local-ipv4')
  284. facts['network']['public_ip'] = metadata.get('public-ipv4')
  285. # TODO: verify that local hostname makes sense and is resolvable
  286. facts['network']['hostname'] = metadata.get('local-hostname')
  287. # TODO: verify that public hostname makes sense and is resolvable
  288. facts['network']['public_hostname'] = metadata.get('public-hostname')
  289. return facts
  290. def normalize_openstack_facts(metadata, facts):
  291. """ Normalize openstack facts
  292. Args:
  293. metadata (dict): provider metadata
  294. facts (dict): facts to update
  295. Returns:
  296. dict: the result of adding the normalized metadata to the provided
  297. facts dict
  298. """
  299. # openstack ec2 compat api does not support network interfaces and
  300. # the version tested on did not include the info in the openstack
  301. # metadata api, should be updated if neutron exposes this.
  302. facts['zone'] = metadata['availability_zone']
  303. local_ipv4 = metadata['ec2_compat']['local-ipv4'].split(',')[0]
  304. facts['network']['ip'] = local_ipv4
  305. facts['network']['public_ip'] = metadata['ec2_compat']['public-ipv4']
  306. # TODO: verify local hostname makes sense and is resolvable
  307. facts['network']['hostname'] = metadata['hostname']
  308. # TODO: verify that public hostname makes sense and is resolvable
  309. pub_h = metadata['ec2_compat']['public-hostname']
  310. facts['network']['public_hostname'] = pub_h
  311. return facts
  312. def normalize_provider_facts(provider, metadata):
  313. """ Normalize provider facts
  314. Args:
  315. provider (str): host provider
  316. metadata (dict): provider metadata
  317. Returns:
  318. dict: the normalized provider facts
  319. """
  320. if provider is None or metadata is None:
  321. return {}
  322. # TODO: test for ipv6_enabled where possible (gce, aws do not support)
  323. # and configure ipv6 facts if available
  324. # TODO: add support for setting user_data if available
  325. facts = dict(name=provider, metadata=metadata,
  326. network=dict(interfaces=[], ipv6_enabled=False))
  327. if provider == 'gce':
  328. facts = normalize_gce_facts(metadata, facts)
  329. elif provider == 'aws':
  330. facts = normalize_aws_facts(metadata, facts)
  331. elif provider == 'openstack':
  332. facts = normalize_openstack_facts(metadata, facts)
  333. return facts
  334. def set_flannel_facts_if_unset(facts):
  335. """ Set flannel facts if not already present in facts dict
  336. dict: the facts dict updated with the flannel facts if
  337. missing
  338. Args:
  339. facts (dict): existing facts
  340. Returns:
  341. dict: the facts dict updated with the flannel
  342. facts if they were not already present
  343. """
  344. if 'common' in facts:
  345. if 'use_flannel' not in facts['common']:
  346. use_flannel = False
  347. facts['common']['use_flannel'] = use_flannel
  348. return facts
  349. def set_nuage_facts_if_unset(facts):
  350. """ Set nuage facts if not already present in facts dict
  351. dict: the facts dict updated with the nuage facts if
  352. missing
  353. Args:
  354. facts (dict): existing facts
  355. Returns:
  356. dict: the facts dict updated with the nuage
  357. facts if they were not already present
  358. """
  359. if 'common' in facts:
  360. if 'use_nuage' not in facts['common']:
  361. use_nuage = False
  362. facts['common']['use_nuage'] = use_nuage
  363. return facts
  364. def set_node_schedulability(facts):
  365. """ Set schedulable facts if not already present in facts dict
  366. Args:
  367. facts (dict): existing facts
  368. Returns:
  369. dict: the facts dict updated with the generated schedulable
  370. facts if they were not already present
  371. """
  372. if 'node' in facts:
  373. if 'schedulable' not in facts['node']:
  374. if 'master' in facts:
  375. facts['node']['schedulable'] = False
  376. else:
  377. facts['node']['schedulable'] = True
  378. return facts
  379. def set_selectors(facts):
  380. """ Set selectors facts if not already present in facts dict
  381. Args:
  382. facts (dict): existing facts
  383. Returns:
  384. dict: the facts dict updated with the generated selectors
  385. facts if they were not already present
  386. """
  387. deployment_type = facts['common']['deployment_type']
  388. if deployment_type == 'online':
  389. selector = "type=infra"
  390. else:
  391. selector = "region=infra"
  392. if 'hosted' not in facts:
  393. facts['hosted'] = {}
  394. if 'router' not in facts['hosted']:
  395. facts['hosted']['router'] = {}
  396. if 'selector' not in facts['hosted']['router'] or facts['hosted']['router']['selector'] in [None, 'None']:
  397. facts['hosted']['router']['selector'] = selector
  398. if 'master' in facts:
  399. if 'infra_nodes' in facts['master']:
  400. if 'registry_selector' not in facts['master']:
  401. facts['master']['registry_selector'] = selector
  402. return facts
  403. def set_metrics_facts_if_unset(facts):
  404. """ Set cluster metrics facts if not already present in facts dict
  405. dict: the facts dict updated with the generated cluster metrics facts if
  406. missing
  407. Args:
  408. facts (dict): existing facts
  409. Returns:
  410. dict: the facts dict updated with the generated cluster metrics
  411. facts if they were not already present
  412. """
  413. if 'common' in facts:
  414. if 'use_cluster_metrics' not in facts['common']:
  415. use_cluster_metrics = False
  416. facts['common']['use_cluster_metrics'] = use_cluster_metrics
  417. return facts
  418. def set_dnsmasq_facts_if_unset(facts):
  419. """ Set dnsmasq facts if not already present in facts
  420. Args:
  421. facts (dict) existing facts
  422. Returns:
  423. facts (dict) updated facts with values set if not previously set
  424. """
  425. if 'common' in facts:
  426. if 'use_dnsmasq' not in facts['common'] and safe_get_bool(facts['common']['version_gte_3_2_or_1_2']):
  427. facts['common']['use_dnsmasq'] = True
  428. else:
  429. facts['common']['use_dnsmasq'] = False
  430. if 'master' in facts and 'dns_port' not in facts['master']:
  431. if safe_get_bool(facts['common']['use_dnsmasq']):
  432. facts['master']['dns_port'] = 8053
  433. else:
  434. facts['master']['dns_port'] = 53
  435. return facts
  436. def set_project_cfg_facts_if_unset(facts):
  437. """ Set Project Configuration facts if not already present in facts dict
  438. dict:
  439. Args:
  440. facts (dict): existing facts
  441. Returns:
  442. dict: the facts dict updated with the generated Project Configuration
  443. facts if they were not already present
  444. """
  445. config = {
  446. 'default_node_selector': '',
  447. 'project_request_message': '',
  448. 'project_request_template': '',
  449. 'mcs_allocator_range': 's0:/2',
  450. 'mcs_labels_per_project': 5,
  451. 'uid_allocator_range': '1000000000-1999999999/10000'
  452. }
  453. if 'master' in facts:
  454. for key, value in config.items():
  455. if key not in facts['master']:
  456. facts['master'][key] = value
  457. return facts
  458. def set_identity_providers_if_unset(facts):
  459. """ Set identity_providers fact if not already present in facts dict
  460. Args:
  461. facts (dict): existing facts
  462. Returns:
  463. dict: the facts dict updated with the generated identity providers
  464. facts if they were not already present
  465. """
  466. if 'master' in facts:
  467. deployment_type = facts['common']['deployment_type']
  468. if 'identity_providers' not in facts['master']:
  469. identity_provider = dict(
  470. name='allow_all', challenge=True, login=True,
  471. kind='AllowAllPasswordIdentityProvider'
  472. )
  473. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  474. identity_provider = dict(
  475. name='deny_all', challenge=True, login=True,
  476. kind='DenyAllPasswordIdentityProvider'
  477. )
  478. facts['master']['identity_providers'] = [identity_provider]
  479. return facts
  480. def set_url_facts_if_unset(facts):
  481. """ Set url facts if not already present in facts dict
  482. Args:
  483. facts (dict): existing facts
  484. Returns:
  485. dict: the facts dict updated with the generated url facts if they
  486. were not already present
  487. """
  488. if 'master' in facts:
  489. hostname = facts['common']['hostname']
  490. cluster_hostname = facts['master'].get('cluster_hostname')
  491. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  492. public_hostname = facts['common']['public_hostname']
  493. api_hostname = cluster_hostname if cluster_hostname else hostname
  494. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  495. console_path = facts['master']['console_path']
  496. etcd_hosts = facts['master']['etcd_hosts']
  497. use_ssl = dict(
  498. api=facts['master']['api_use_ssl'],
  499. public_api=facts['master']['api_use_ssl'],
  500. loopback_api=facts['master']['api_use_ssl'],
  501. console=facts['master']['console_use_ssl'],
  502. public_console=facts['master']['console_use_ssl'],
  503. etcd=facts['master']['etcd_use_ssl']
  504. )
  505. ports = dict(
  506. api=facts['master']['api_port'],
  507. public_api=facts['master']['api_port'],
  508. loopback_api=facts['master']['api_port'],
  509. console=facts['master']['console_port'],
  510. public_console=facts['master']['console_port'],
  511. etcd=facts['master']['etcd_port'],
  512. )
  513. etcd_urls = []
  514. if etcd_hosts != '':
  515. facts['master']['etcd_port'] = ports['etcd']
  516. facts['master']['embedded_etcd'] = False
  517. for host in etcd_hosts:
  518. etcd_urls.append(format_url(use_ssl['etcd'], host,
  519. ports['etcd']))
  520. else:
  521. etcd_urls = [format_url(use_ssl['etcd'], hostname,
  522. ports['etcd'])]
  523. facts['master'].setdefault('etcd_urls', etcd_urls)
  524. prefix_hosts = [('api', api_hostname),
  525. ('public_api', api_public_hostname),
  526. ('loopback_api', hostname)]
  527. for prefix, host in prefix_hosts:
  528. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  529. host,
  530. ports[prefix]))
  531. r_lhn = "{0}:{1}".format(hostname, ports['api']).replace('.', '-')
  532. r_lhu = "system:openshift-master/{0}:{1}".format(api_hostname, ports['api']).replace('.', '-')
  533. facts['master'].setdefault('loopback_cluster_name', r_lhn)
  534. facts['master'].setdefault('loopback_context_name', "default/{0}/system:openshift-master".format(r_lhn))
  535. facts['master'].setdefault('loopback_user', r_lhu)
  536. prefix_hosts = [('console', api_hostname), ('public_console', api_public_hostname)]
  537. for prefix, host in prefix_hosts:
  538. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  539. host,
  540. ports[prefix],
  541. console_path))
  542. return facts
  543. def set_aggregate_facts(facts):
  544. """ Set aggregate facts
  545. Args:
  546. facts (dict): existing facts
  547. Returns:
  548. dict: the facts dict updated with aggregated facts
  549. """
  550. all_hostnames = set()
  551. internal_hostnames = set()
  552. kube_svc_ip = first_ip(facts['common']['portal_net'])
  553. if 'common' in facts:
  554. all_hostnames.add(facts['common']['hostname'])
  555. all_hostnames.add(facts['common']['public_hostname'])
  556. all_hostnames.add(facts['common']['ip'])
  557. all_hostnames.add(facts['common']['public_ip'])
  558. facts['common']['kube_svc_ip'] = kube_svc_ip
  559. internal_hostnames.add(facts['common']['hostname'])
  560. internal_hostnames.add(facts['common']['ip'])
  561. cluster_domain = facts['common']['dns_domain']
  562. if 'master' in facts:
  563. if 'cluster_hostname' in facts['master']:
  564. all_hostnames.add(facts['master']['cluster_hostname'])
  565. if 'cluster_public_hostname' in facts['master']:
  566. all_hostnames.add(facts['master']['cluster_public_hostname'])
  567. svc_names = ['openshift', 'openshift.default', 'openshift.default.svc',
  568. 'openshift.default.svc.' + cluster_domain, 'kubernetes', 'kubernetes.default',
  569. 'kubernetes.default.svc', 'kubernetes.default.svc.' + cluster_domain]
  570. all_hostnames.update(svc_names)
  571. internal_hostnames.update(svc_names)
  572. all_hostnames.add(kube_svc_ip)
  573. internal_hostnames.add(kube_svc_ip)
  574. facts['common']['all_hostnames'] = list(all_hostnames)
  575. facts['common']['internal_hostnames'] = list(internal_hostnames)
  576. return facts
  577. def set_etcd_facts_if_unset(facts):
  578. """
  579. If using embedded etcd, loads the data directory from master-config.yaml.
  580. If using standalone etcd, loads ETCD_DATA_DIR from etcd.conf.
  581. If anything goes wrong parsing these, the fact will not be set.
  582. """
  583. if 'master' in facts and safe_get_bool(facts['master']['embedded_etcd']):
  584. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  585. if 'etcd_data_dir' not in etcd_facts:
  586. try:
  587. # Parse master config to find actual etcd data dir:
  588. master_cfg_path = os.path.join(facts['common']['config_base'],
  589. 'master/master-config.yaml')
  590. master_cfg_f = open(master_cfg_path, 'r')
  591. config = yaml.safe_load(master_cfg_f.read())
  592. master_cfg_f.close()
  593. etcd_facts['etcd_data_dir'] = \
  594. config['etcdConfig']['storageDirectory']
  595. facts['etcd'] = etcd_facts
  596. # We don't want exceptions bubbling up here:
  597. # pylint: disable=broad-except
  598. except Exception:
  599. pass
  600. else:
  601. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  602. # Read ETCD_DATA_DIR from /etc/etcd/etcd.conf:
  603. try:
  604. # Add a fake section for parsing:
  605. ini_str = unicode('[root]\n' + open('/etc/etcd/etcd.conf', 'r').read(), 'utf-8')
  606. ini_fp = io.StringIO(ini_str)
  607. config = ConfigParser.RawConfigParser()
  608. config.readfp(ini_fp)
  609. etcd_data_dir = config.get('root', 'ETCD_DATA_DIR')
  610. if etcd_data_dir.startswith('"') and etcd_data_dir.endswith('"'):
  611. etcd_data_dir = etcd_data_dir[1:-1]
  612. etcd_facts['etcd_data_dir'] = etcd_data_dir
  613. facts['etcd'] = etcd_facts
  614. # We don't want exceptions bubbling up here:
  615. # pylint: disable=broad-except
  616. except Exception:
  617. pass
  618. return facts
  619. def set_deployment_facts_if_unset(facts):
  620. """ Set Facts that vary based on deployment_type. This currently
  621. includes common.service_type, common.config_base, master.registry_url,
  622. node.registry_url, node.storage_plugin_deps
  623. Args:
  624. facts (dict): existing facts
  625. Returns:
  626. dict: the facts dict updated with the generated deployment_type
  627. facts
  628. """
  629. # disabled to avoid breaking up facts related to deployment type into
  630. # multiple methods for now.
  631. # pylint: disable=too-many-statements, too-many-branches
  632. if 'common' in facts:
  633. deployment_type = facts['common']['deployment_type']
  634. if 'service_type' not in facts['common']:
  635. service_type = 'atomic-openshift'
  636. if deployment_type == 'origin':
  637. service_type = 'origin'
  638. elif deployment_type in ['enterprise']:
  639. service_type = 'openshift'
  640. facts['common']['service_type'] = service_type
  641. if 'config_base' not in facts['common']:
  642. config_base = '/etc/origin'
  643. if deployment_type in ['enterprise']:
  644. config_base = '/etc/openshift'
  645. # Handle upgrade scenarios when symlinks don't yet exist:
  646. if not os.path.exists(config_base) and os.path.exists('/etc/openshift'):
  647. config_base = '/etc/openshift'
  648. facts['common']['config_base'] = config_base
  649. if 'data_dir' not in facts['common']:
  650. data_dir = '/var/lib/origin'
  651. if deployment_type in ['enterprise']:
  652. data_dir = '/var/lib/openshift'
  653. # Handle upgrade scenarios when symlinks don't yet exist:
  654. if not os.path.exists(data_dir) and os.path.exists('/var/lib/openshift'):
  655. data_dir = '/var/lib/openshift'
  656. facts['common']['data_dir'] = data_dir
  657. if 'docker' in facts:
  658. deployment_type = facts['common']['deployment_type']
  659. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  660. addtl_regs = facts['docker'].get('additional_registries', [])
  661. ent_reg = 'registry.access.redhat.com'
  662. if ent_reg not in addtl_regs:
  663. facts['docker']['additional_registries'] = addtl_regs + [ent_reg]
  664. for role in ('master', 'node'):
  665. if role in facts:
  666. deployment_type = facts['common']['deployment_type']
  667. if 'registry_url' not in facts[role]:
  668. registry_url = 'openshift/origin-${component}:${version}'
  669. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  670. registry_url = 'openshift3/ose-${component}:${version}'
  671. elif deployment_type == 'atomic-enterprise':
  672. registry_url = 'aep3_beta/aep-${component}:${version}'
  673. facts[role]['registry_url'] = registry_url
  674. if 'master' in facts:
  675. deployment_type = facts['common']['deployment_type']
  676. openshift_features = ['Builder', 'S2IBuilder', 'WebConsole']
  677. if 'disabled_features' in facts['master']:
  678. if deployment_type == 'atomic-enterprise':
  679. curr_disabled_features = set(facts['master']['disabled_features'])
  680. facts['master']['disabled_features'] = list(curr_disabled_features.union(openshift_features))
  681. else:
  682. if deployment_type == 'atomic-enterprise':
  683. facts['master']['disabled_features'] = openshift_features
  684. if 'node' in facts:
  685. deployment_type = facts['common']['deployment_type']
  686. if 'storage_plugin_deps' not in facts['node']:
  687. if deployment_type in ['openshift-enterprise', 'atomic-enterprise', 'origin']:
  688. facts['node']['storage_plugin_deps'] = ['ceph', 'glusterfs', 'iscsi']
  689. else:
  690. facts['node']['storage_plugin_deps'] = []
  691. return facts
  692. def set_version_facts_if_unset(facts):
  693. """ Set version facts. This currently includes common.version and
  694. common.version_gte_3_1_or_1_1.
  695. Args:
  696. facts (dict): existing facts
  697. Returns:
  698. dict: the facts dict updated with version facts.
  699. """
  700. if 'common' in facts:
  701. deployment_type = facts['common']['deployment_type']
  702. version = get_openshift_version(facts)
  703. if version:
  704. facts['common']['version'] = version
  705. if deployment_type == 'origin':
  706. version_gte_3_1_or_1_1 = LooseVersion(version) >= LooseVersion('1.1.0')
  707. version_gte_3_1_1_or_1_1_1 = LooseVersion(version) >= LooseVersion('1.1.1')
  708. version_gte_3_2_or_1_2 = LooseVersion(version) >= LooseVersion('1.2.0')
  709. version_gte_3_3_or_1_3 = LooseVersion(version) >= LooseVersion('1.3.0')
  710. else:
  711. version_gte_3_1_or_1_1 = LooseVersion(version) >= LooseVersion('3.0.2.905')
  712. version_gte_3_1_1_or_1_1_1 = LooseVersion(version) >= LooseVersion('3.1.1')
  713. version_gte_3_2_or_1_2 = LooseVersion(version) >= LooseVersion('3.1.1.901')
  714. version_gte_3_3_or_1_3 = LooseVersion(version) >= LooseVersion('3.3.0')
  715. else:
  716. version_gte_3_1_or_1_1 = True
  717. version_gte_3_1_1_or_1_1_1 = True
  718. version_gte_3_2_or_1_2 = True
  719. version_gte_3_3_or_1_3 = False
  720. facts['common']['version_gte_3_1_or_1_1'] = version_gte_3_1_or_1_1
  721. facts['common']['version_gte_3_1_1_or_1_1_1'] = version_gte_3_1_1_or_1_1_1
  722. facts['common']['version_gte_3_2_or_1_2'] = version_gte_3_2_or_1_2
  723. facts['common']['version_gte_3_3_or_1_3'] = version_gte_3_3_or_1_3
  724. if version_gte_3_3_or_1_3:
  725. examples_content_version = 'v1.3'
  726. elif version_gte_3_2_or_1_2:
  727. examples_content_version = 'v1.2'
  728. elif version_gte_3_1_or_1_1:
  729. examples_content_version = 'v1.1'
  730. else:
  731. examples_content_version = 'v1.0'
  732. facts['common']['examples_content_version'] = examples_content_version
  733. return facts
  734. def set_manageiq_facts_if_unset(facts):
  735. """ Set manageiq facts. This currently includes common.use_manageiq.
  736. Args:
  737. facts (dict): existing facts
  738. Returns:
  739. dict: the facts dict updated with version facts.
  740. Raises:
  741. OpenShiftFactsInternalError:
  742. """
  743. if 'common' not in facts:
  744. if 'version_gte_3_1_or_1_1' not in facts['common']:
  745. raise OpenShiftFactsInternalError(
  746. "Invalid invocation: The required facts are not set"
  747. )
  748. if 'use_manageiq' not in facts['common']:
  749. facts['common']['use_manageiq'] = facts['common']['version_gte_3_1_or_1_1']
  750. return facts
  751. def set_sdn_facts_if_unset(facts, system_facts):
  752. """ Set sdn facts if not already present in facts dict
  753. Args:
  754. facts (dict): existing facts
  755. system_facts (dict): ansible_facts
  756. Returns:
  757. dict: the facts dict updated with the generated sdn facts if they
  758. were not already present
  759. """
  760. if 'common' in facts:
  761. use_sdn = facts['common']['use_openshift_sdn']
  762. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  763. use_sdn = safe_get_bool(use_sdn)
  764. facts['common']['use_openshift_sdn'] = use_sdn
  765. if 'sdn_network_plugin_name' not in facts['common']:
  766. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  767. facts['common']['sdn_network_plugin_name'] = plugin
  768. if 'master' in facts:
  769. if 'sdn_cluster_network_cidr' not in facts['master']:
  770. facts['master']['sdn_cluster_network_cidr'] = '10.1.0.0/16'
  771. if 'sdn_host_subnet_length' not in facts['master']:
  772. facts['master']['sdn_host_subnet_length'] = '8'
  773. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  774. node_ip = facts['common']['ip']
  775. # default MTU if interface MTU cannot be detected
  776. facts['node']['sdn_mtu'] = '1450'
  777. for val in system_facts.itervalues():
  778. if isinstance(val, dict) and 'mtu' in val:
  779. mtu = val['mtu']
  780. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  781. facts['node']['sdn_mtu'] = str(mtu - 50)
  782. return facts
  783. def migrate_oauth_template_facts(facts):
  784. """
  785. Migrate an old oauth template fact to a newer format if it's present.
  786. The legacy 'oauth_template' fact was just a filename, and assumed you were
  787. setting the 'login' template.
  788. The new pluralized 'oauth_templates' fact is a dict mapping the template
  789. name to a filename.
  790. Simplify the code after this by merging the old fact into the new.
  791. """
  792. if 'master' in facts and 'oauth_template' in facts['master']:
  793. if 'oauth_templates' not in facts['master']:
  794. facts['master']['oauth_templates'] = {"login": facts['master']['oauth_template']}
  795. elif 'login' not in facts['master']['oauth_templates']:
  796. facts['master']['oauth_templates']['login'] = facts['master']['oauth_template']
  797. return facts
  798. def format_url(use_ssl, hostname, port, path=''):
  799. """ Format url based on ssl flag, hostname, port and path
  800. Args:
  801. use_ssl (bool): is ssl enabled
  802. hostname (str): hostname
  803. port (str): port
  804. path (str): url path
  805. Returns:
  806. str: The generated url string
  807. """
  808. scheme = 'https' if use_ssl else 'http'
  809. netloc = hostname
  810. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  811. netloc += ":%s" % port
  812. return urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  813. def get_current_config(facts):
  814. """ Get current openshift config
  815. Args:
  816. facts (dict): existing facts
  817. Returns:
  818. dict: the facts dict updated with the current openshift config
  819. """
  820. current_config = dict()
  821. roles = [role for role in facts if role not in ['common', 'provider']]
  822. for role in roles:
  823. if 'roles' in current_config:
  824. current_config['roles'].append(role)
  825. else:
  826. current_config['roles'] = [role]
  827. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  828. # determine the location of files.
  829. # TODO: I suspect this isn't working right now, but it doesn't prevent
  830. # anything from working properly as far as I can tell, perhaps because
  831. # we override the kubeconfig path everywhere we use it?
  832. # Query kubeconfig settings
  833. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  834. if role == 'node':
  835. kubeconfig_dir = os.path.join(
  836. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  837. )
  838. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  839. if (os.path.isfile('/usr/bin/openshift')
  840. and os.path.isfile(kubeconfig_path)):
  841. try:
  842. _, output, _ = module.run_command(
  843. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  844. "json", "--kubeconfig=%s" % kubeconfig_path],
  845. check_rc=False
  846. )
  847. config = json.loads(output)
  848. cad = 'certificate-authority-data'
  849. try:
  850. for cluster in config['clusters']:
  851. config['clusters'][cluster][cad] = 'masked'
  852. except KeyError:
  853. pass
  854. try:
  855. for user in config['users']:
  856. config['users'][user][cad] = 'masked'
  857. config['users'][user]['client-key-data'] = 'masked'
  858. except KeyError:
  859. pass
  860. current_config['kubeconfig'] = config
  861. # override pylint broad-except warning, since we do not want
  862. # to bubble up any exceptions if oc config view
  863. # fails
  864. # pylint: disable=broad-except
  865. except Exception:
  866. pass
  867. return current_config
  868. def build_kubelet_args(facts):
  869. """ Build node kubelet_args """
  870. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  871. 'cloudprovider')
  872. if 'node' in facts:
  873. kubelet_args = {}
  874. if 'cloudprovider' in facts:
  875. if 'kind' in facts['cloudprovider']:
  876. if facts['cloudprovider']['kind'] == 'aws':
  877. kubelet_args['cloud-provider'] = ['aws']
  878. kubelet_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  879. if facts['cloudprovider']['kind'] == 'openstack':
  880. kubelet_args['cloud-provider'] = ['openstack']
  881. kubelet_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  882. if kubelet_args != {}:
  883. facts = merge_facts({'node': {'kubelet_args': kubelet_args}}, facts, [], [])
  884. return facts
  885. def build_controller_args(facts):
  886. """ Build master controller_args """
  887. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  888. 'cloudprovider')
  889. if 'master' in facts:
  890. controller_args = {}
  891. if 'cloudprovider' in facts:
  892. if 'kind' in facts['cloudprovider']:
  893. if facts['cloudprovider']['kind'] == 'aws':
  894. controller_args['cloud-provider'] = ['aws']
  895. controller_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  896. if facts['cloudprovider']['kind'] == 'openstack':
  897. controller_args['cloud-provider'] = ['openstack']
  898. controller_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  899. if controller_args != {}:
  900. facts = merge_facts({'master': {'controller_args': controller_args}}, facts, [], [])
  901. return facts
  902. def build_api_server_args(facts):
  903. """ Build master api_server_args """
  904. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  905. 'cloudprovider')
  906. if 'master' in facts:
  907. api_server_args = {}
  908. if 'cloudprovider' in facts:
  909. if 'kind' in facts['cloudprovider']:
  910. if facts['cloudprovider']['kind'] == 'aws':
  911. api_server_args['cloud-provider'] = ['aws']
  912. api_server_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  913. if facts['cloudprovider']['kind'] == 'openstack':
  914. api_server_args['cloud-provider'] = ['openstack']
  915. api_server_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  916. if api_server_args != {}:
  917. facts = merge_facts({'master': {'api_server_args': api_server_args}}, facts, [], [])
  918. return facts
  919. def is_service_running(service):
  920. """ Queries systemd through dbus to see if the service is running """
  921. service_running = False
  922. bus = SystemBus()
  923. systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
  924. manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
  925. try:
  926. service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
  927. service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
  928. service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
  929. service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
  930. service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
  931. if service_load_state == 'loaded' and service_active_state == 'active':
  932. service_running = True
  933. except DBusException:
  934. pass
  935. return service_running
  936. def get_version_output(binary, version_cmd):
  937. """ runs and returns the version output for a command """
  938. cmd = []
  939. for item in (binary, version_cmd):
  940. if isinstance(item, list):
  941. cmd.extend(item)
  942. else:
  943. cmd.append(item)
  944. if os.path.isfile(cmd[0]):
  945. _, output, _ = module.run_command(cmd)
  946. return output
  947. def get_docker_version_info():
  948. """ Parses and returns the docker version info """
  949. result = None
  950. if is_service_running('docker'):
  951. version_info = yaml.safe_load(get_version_output('/usr/bin/docker', 'version'))
  952. if 'Server' in version_info:
  953. result = {
  954. 'api_version': version_info['Server']['API version'],
  955. 'version': version_info['Server']['Version']
  956. }
  957. return result
  958. def get_openshift_version(facts):
  959. """ Get current version of openshift on the host.
  960. Checks a variety of ways ranging from fastest to slowest.
  961. Args:
  962. facts (dict): existing facts
  963. optional cli_image for pulling the version number
  964. Returns:
  965. version: the current openshift version
  966. """
  967. version = None
  968. # No need to run this method repeatedly on a system if we already know the
  969. # version
  970. if 'common' in facts:
  971. if 'version' in facts['common'] and facts['common']['version'] is not None:
  972. return facts['common']['version']
  973. if os.path.isfile('/usr/bin/openshift'):
  974. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  975. version = parse_openshift_version(output)
  976. elif 'common' in facts and 'is_containerized' in facts['common']:
  977. version = get_containerized_openshift_version(facts)
  978. # Handle containerized masters that have not yet been configured as a node.
  979. # This can be very slow and may get re-run multiple times, so we only use this
  980. # if other methods failed to find a version.
  981. if not version and os.path.isfile('/usr/local/bin/openshift'):
  982. _, output, _ = module.run_command(['/usr/local/bin/openshift', 'version'])
  983. version = parse_openshift_version(output)
  984. return version
  985. def get_containerized_openshift_version(facts):
  986. # If containerized, see if we can determine the installed version via the systemd environment files:
  987. for filename in ['/etc/sysconfig/%s-master', '/etc/sysconfig/%s-node']:
  988. env_file = filename % facts['common']['service_type']
  989. if not os.path.exists(env_file):
  990. continue
  991. with open(env_file) as f:
  992. for line in f:
  993. if line.startswith("IMAGE_VERSION="):
  994. tag = line[len("IMAGE_VERSION="):].strip()
  995. # Remove leading "v" and any trailing release info, we just want
  996. # a version number here:
  997. version = tag[1:].split("-")[0]
  998. return version
  999. return None
  1000. def parse_openshift_version(output):
  1001. """ Apply provider facts to supplied facts dict
  1002. Args:
  1003. string: output of 'openshift version'
  1004. Returns:
  1005. string: the version number
  1006. """
  1007. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  1008. ver = versions.get('openshift', '')
  1009. # Remove trailing build number and commit hash from older versions, we need to return a straight
  1010. # w.x.y.z version here for use as openshift_version throughout the playbooks/roles. (i.e. 3.1.1.6-64-g80b61da)
  1011. ver = ver.split('-')[0]
  1012. return ver
  1013. def apply_provider_facts(facts, provider_facts):
  1014. """ Apply provider facts to supplied facts dict
  1015. Args:
  1016. facts (dict): facts dict to update
  1017. provider_facts (dict): provider facts to apply
  1018. roles: host roles
  1019. Returns:
  1020. dict: the merged facts
  1021. """
  1022. if not provider_facts:
  1023. return facts
  1024. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  1025. for h_var, ip_var in common_vars:
  1026. ip_value = provider_facts['network'].get(ip_var)
  1027. if ip_value:
  1028. facts['common'][ip_var] = ip_value
  1029. facts['common'][h_var] = choose_hostname(
  1030. [provider_facts['network'].get(h_var)],
  1031. facts['common'][ip_var]
  1032. )
  1033. facts['provider'] = provider_facts
  1034. return facts
  1035. # Disabling pylint too many branches. This function needs refactored
  1036. # but is a very core part of openshift_facts.
  1037. # pylint: disable=too-many-branches
  1038. def merge_facts(orig, new, additive_facts_to_overwrite, protected_facts_to_overwrite):
  1039. """ Recursively merge facts dicts
  1040. Args:
  1041. orig (dict): existing facts
  1042. new (dict): facts to update
  1043. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1044. '.' notation ex: ['master.named_certificates']
  1045. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1046. '.' notation ex: ['master.master_count']
  1047. Returns:
  1048. dict: the merged facts
  1049. """
  1050. additive_facts = ['named_certificates']
  1051. protected_facts = ['ha', 'master_count']
  1052. # Facts we do not ever want to merge. These originate in inventory variables
  1053. # and contain JSON dicts. We don't ever want to trigger a merge
  1054. # here, just completely overwrite with the new if they are present there.
  1055. inventory_json_facts = ['admission_plugin_config',
  1056. 'kube_admission_plugin_config',
  1057. 'image_policy_config']
  1058. facts = dict()
  1059. for key, value in orig.iteritems():
  1060. # Key exists in both old and new facts.
  1061. if key in new:
  1062. if key in inventory_json_facts:
  1063. # Watchout for JSON facts that sometimes load as strings.
  1064. # (can happen if the JSON contains a boolean)
  1065. if isinstance(new[key], basestring):
  1066. facts[key] = yaml.safe_load(new[key])
  1067. else:
  1068. facts[key] = copy.deepcopy(new[key])
  1069. # Continue to recurse if old and new fact is a dictionary.
  1070. elif isinstance(value, dict) and isinstance(new[key], dict):
  1071. # Collect the subset of additive facts to overwrite if
  1072. # key matches. These will be passed to the subsequent
  1073. # merge_facts call.
  1074. relevant_additive_facts = []
  1075. for item in additive_facts_to_overwrite:
  1076. if '.' in item and item.startswith(key + '.'):
  1077. relevant_additive_facts.append(item)
  1078. # Collect the subset of protected facts to overwrite
  1079. # if key matches. These will be passed to the
  1080. # subsequent merge_facts call.
  1081. relevant_protected_facts = []
  1082. for item in protected_facts_to_overwrite:
  1083. if '.' in item and item.startswith(key + '.'):
  1084. relevant_protected_facts.append(item)
  1085. facts[key] = merge_facts(value, new[key], relevant_additive_facts, relevant_protected_facts)
  1086. # Key matches an additive fact and we are not overwriting
  1087. # it so we will append the new value to the existing value.
  1088. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  1089. if isinstance(value, list) and isinstance(new[key], list):
  1090. new_fact = []
  1091. for item in copy.deepcopy(value) + copy.deepcopy(new[key]):
  1092. if item not in new_fact:
  1093. new_fact.append(item)
  1094. facts[key] = new_fact
  1095. # Key matches a protected fact and we are not overwriting
  1096. # it so we will determine if it is okay to change this
  1097. # fact.
  1098. elif key in protected_facts and key not in [x.split('.')[-1] for x in protected_facts_to_overwrite]:
  1099. # The master count (int) can only increase unless it
  1100. # has been passed as a protected fact to overwrite.
  1101. if key == 'master_count':
  1102. if int(value) <= int(new[key]):
  1103. facts[key] = copy.deepcopy(new[key])
  1104. else:
  1105. module.fail_json(msg='openshift_facts received a lower value for openshift.master.master_count')
  1106. # ha (bool) can not change unless it has been passed
  1107. # as a protected fact to overwrite.
  1108. if key == 'ha':
  1109. if safe_get_bool(value) != safe_get_bool(new[key]):
  1110. module.fail_json(msg='openshift_facts received a different value for openshift.master.ha')
  1111. else:
  1112. facts[key] = value
  1113. # No other condition has been met. Overwrite the old fact
  1114. # with the new value.
  1115. else:
  1116. facts[key] = copy.deepcopy(new[key])
  1117. # Key isn't in new so add it to facts to keep it.
  1118. else:
  1119. facts[key] = copy.deepcopy(value)
  1120. new_keys = set(new.keys()) - set(orig.keys())
  1121. for key in new_keys:
  1122. # Watchout for JSON facts that sometimes load as strings.
  1123. # (can happen if the JSON contains a boolean)
  1124. if key in inventory_json_facts and isinstance(new[key], basestring):
  1125. facts[key] = yaml.safe_load(new[key])
  1126. else:
  1127. facts[key] = copy.deepcopy(new[key])
  1128. return facts
  1129. def save_local_facts(filename, facts):
  1130. """ Save local facts
  1131. Args:
  1132. filename (str): local facts file
  1133. facts (dict): facts to set
  1134. """
  1135. try:
  1136. fact_dir = os.path.dirname(filename)
  1137. if not os.path.exists(fact_dir):
  1138. os.makedirs(fact_dir)
  1139. with open(filename, 'w') as fact_file:
  1140. fact_file.write(module.jsonify(facts))
  1141. os.chmod(filename, 0o600)
  1142. except (IOError, OSError) as ex:
  1143. raise OpenShiftFactsFileWriteError(
  1144. "Could not create fact file: %s, error: %s" % (filename, ex)
  1145. )
  1146. def get_local_facts_from_file(filename):
  1147. """ Retrieve local facts from fact file
  1148. Args:
  1149. filename (str): local facts file
  1150. Returns:
  1151. dict: the retrieved facts
  1152. """
  1153. local_facts = dict()
  1154. try:
  1155. # Handle conversion of INI style facts file to json style
  1156. ini_facts = ConfigParser.SafeConfigParser()
  1157. ini_facts.read(filename)
  1158. for section in ini_facts.sections():
  1159. local_facts[section] = dict()
  1160. for key, value in ini_facts.items(section):
  1161. local_facts[section][key] = value
  1162. except (ConfigParser.MissingSectionHeaderError,
  1163. ConfigParser.ParsingError):
  1164. try:
  1165. with open(filename, 'r') as facts_file:
  1166. local_facts = json.load(facts_file)
  1167. except (ValueError, IOError):
  1168. pass
  1169. return local_facts
  1170. def sort_unique(alist):
  1171. """ Sorts and de-dupes a list
  1172. Args:
  1173. list: a list
  1174. Returns:
  1175. list: a sorted de-duped list
  1176. """
  1177. alist.sort()
  1178. out = list()
  1179. for i in alist:
  1180. if i not in out:
  1181. out.append(i)
  1182. return out
  1183. def safe_get_bool(fact):
  1184. """ Get a boolean fact safely.
  1185. Args:
  1186. facts: fact to convert
  1187. Returns:
  1188. bool: given fact as a bool
  1189. """
  1190. return bool(strtobool(str(fact)))
  1191. def set_proxy_facts(facts):
  1192. """ Set global proxy facts and promote defaults from http_proxy, https_proxy,
  1193. no_proxy to the more specific builddefaults and builddefaults_git vars.
  1194. 1. http_proxy, https_proxy, no_proxy
  1195. 2. builddefaults_*
  1196. 3. builddefaults_git_*
  1197. Args:
  1198. facts(dict): existing facts
  1199. Returns:
  1200. facts(dict): Updated facts with missing values
  1201. """
  1202. if 'common' in facts:
  1203. common = facts['common']
  1204. if 'http_proxy' in common or 'https_proxy' in common:
  1205. if 'no_proxy' in common and \
  1206. isinstance(common['no_proxy'], basestring):
  1207. common['no_proxy'] = common['no_proxy'].split(",")
  1208. elif 'no_proxy' not in common:
  1209. common['no_proxy'] = []
  1210. if 'generate_no_proxy_hosts' in common and \
  1211. safe_get_bool(common['generate_no_proxy_hosts']):
  1212. if 'no_proxy_internal_hostnames' in common:
  1213. common['no_proxy'].extend(common['no_proxy_internal_hostnames'].split(','))
  1214. common['no_proxy'].append('.' + common['dns_domain'])
  1215. # We always add ourselves no matter what
  1216. common['no_proxy'].append(common['hostname'])
  1217. common['no_proxy'] = sort_unique(common['no_proxy'])
  1218. facts['common'] = common
  1219. if 'builddefaults' in facts:
  1220. builddefaults = facts['builddefaults']
  1221. common = facts['common']
  1222. # Copy values from common to builddefaults
  1223. if 'http_proxy' not in builddefaults and 'http_proxy' in common:
  1224. builddefaults['http_proxy'] = common['http_proxy']
  1225. if 'https_proxy' not in builddefaults and 'https_proxy' in common:
  1226. builddefaults['https_proxy'] = common['https_proxy']
  1227. if 'no_proxy' not in builddefaults and 'no_proxy' in common:
  1228. builddefaults['no_proxy'] = common['no_proxy']
  1229. if 'git_http_proxy' not in builddefaults and 'http_proxy' in builddefaults:
  1230. builddefaults['git_http_proxy'] = builddefaults['http_proxy']
  1231. if 'git_https_proxy' not in builddefaults and 'https_proxy' in builddefaults:
  1232. builddefaults['git_https_proxy'] = builddefaults['https_proxy']
  1233. # If we're actually defining a proxy config then create kube_admission_plugin_config
  1234. # if it doesn't exist, then merge builddefaults[config] structure
  1235. # into kube_admission_plugin_config
  1236. if 'kube_admission_plugin_config' not in facts['master']:
  1237. facts['master']['kube_admission_plugin_config'] = dict()
  1238. if 'config' in builddefaults and ('http_proxy' in builddefaults or \
  1239. 'https_proxy' in builddefaults):
  1240. facts['master']['kube_admission_plugin_config'].update(builddefaults['config'])
  1241. facts['builddefaults'] = builddefaults
  1242. return facts
  1243. # pylint: disable=too-many-statements
  1244. def set_container_facts_if_unset(facts):
  1245. """ Set containerized facts.
  1246. Args:
  1247. facts (dict): existing facts
  1248. Returns:
  1249. dict: the facts dict updated with the generated containerization
  1250. facts
  1251. """
  1252. deployment_type = facts['common']['deployment_type']
  1253. if deployment_type in ['enterprise', 'openshift-enterprise']:
  1254. master_image = 'openshift3/ose'
  1255. cli_image = master_image
  1256. node_image = 'openshift3/node'
  1257. ovs_image = 'openshift3/openvswitch'
  1258. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1259. pod_image = 'openshift3/ose-pod'
  1260. router_image = 'openshift3/ose-haproxy-router'
  1261. registry_image = 'openshift3/ose-docker-registry'
  1262. deployer_image = 'openshift3/ose-deployer'
  1263. elif deployment_type == 'atomic-enterprise':
  1264. master_image = 'aep3_beta/aep'
  1265. cli_image = master_image
  1266. node_image = 'aep3_beta/node'
  1267. ovs_image = 'aep3_beta/openvswitch'
  1268. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1269. pod_image = 'aep3_beta/aep-pod'
  1270. router_image = 'aep3_beta/aep-haproxy-router'
  1271. registry_image = 'aep3_beta/aep-docker-registry'
  1272. deployer_image = 'aep3_beta/aep-deployer'
  1273. else:
  1274. master_image = 'openshift/origin'
  1275. cli_image = master_image
  1276. node_image = 'openshift/node'
  1277. ovs_image = 'openshift/openvswitch'
  1278. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1279. pod_image = 'openshift/origin-pod'
  1280. router_image = 'openshift/origin-haproxy-router'
  1281. registry_image = 'openshift/origin-docker-registry'
  1282. deployer_image = 'openshift/origin-deployer'
  1283. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  1284. if 'is_containerized' not in facts['common']:
  1285. facts['common']['is_containerized'] = facts['common']['is_atomic']
  1286. if 'cli_image' not in facts['common']:
  1287. facts['common']['cli_image'] = cli_image
  1288. if 'pod_image' not in facts['common']:
  1289. facts['common']['pod_image'] = pod_image
  1290. if 'router_image' not in facts['common']:
  1291. facts['common']['router_image'] = router_image
  1292. if 'registry_image' not in facts['common']:
  1293. facts['common']['registry_image'] = registry_image
  1294. if 'deployer_image' not in facts['common']:
  1295. facts['common']['deployer_image'] = deployer_image
  1296. if 'etcd' in facts and 'etcd_image' not in facts['etcd']:
  1297. facts['etcd']['etcd_image'] = etcd_image
  1298. if 'master' in facts and 'master_image' not in facts['master']:
  1299. facts['master']['master_image'] = master_image
  1300. if 'node' in facts:
  1301. if 'node_image' not in facts['node']:
  1302. facts['node']['node_image'] = node_image
  1303. if 'ovs_image' not in facts['node']:
  1304. facts['node']['ovs_image'] = ovs_image
  1305. if safe_get_bool(facts['common']['is_containerized']):
  1306. facts['common']['admin_binary'] = '/usr/local/bin/oadm'
  1307. facts['common']['client_binary'] = '/usr/local/bin/oc'
  1308. return facts
  1309. def set_installed_variant_rpm_facts(facts):
  1310. """ Set RPM facts of installed variant
  1311. Args:
  1312. facts (dict): existing facts
  1313. Returns:
  1314. dict: the facts dict updated with installed_variant_rpms
  1315. """
  1316. installed_rpms = []
  1317. for base_rpm in ['openshift', 'atomic-openshift', 'origin']:
  1318. optional_rpms = ['master', 'node', 'clients', 'sdn-ovs']
  1319. variant_rpms = [base_rpm] + \
  1320. ['{0}-{1}'.format(base_rpm, r) for r in optional_rpms] + \
  1321. ['tuned-profiles-%s-node' % base_rpm]
  1322. for rpm in variant_rpms:
  1323. exit_code, _, _ = module.run_command(['rpm', '-q', rpm])
  1324. if exit_code == 0:
  1325. installed_rpms.append(rpm)
  1326. facts['common']['installed_variant_rpms'] = installed_rpms
  1327. return facts
  1328. class OpenShiftFactsInternalError(Exception):
  1329. """Origin Facts Error"""
  1330. pass
  1331. class OpenShiftFactsUnsupportedRoleError(Exception):
  1332. """Origin Facts Unsupported Role Error"""
  1333. pass
  1334. class OpenShiftFactsFileWriteError(Exception):
  1335. """Origin Facts File Write Error"""
  1336. pass
  1337. class OpenShiftFactsMetadataUnavailableError(Exception):
  1338. """Origin Facts Metadata Unavailable Error"""
  1339. pass
  1340. class OpenShiftFacts(object):
  1341. """ Origin Facts
  1342. Attributes:
  1343. facts (dict): facts for the host
  1344. Args:
  1345. module (AnsibleModule): an AnsibleModule object
  1346. role (str): role for setting local facts
  1347. filename (str): local facts file to use
  1348. local_facts (dict): local facts to set
  1349. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1350. '.' notation ex: ['master.named_certificates']
  1351. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1352. '.' notation ex: ['master.master_count']
  1353. Raises:
  1354. OpenShiftFactsUnsupportedRoleError:
  1355. """
  1356. known_roles = ['builddefaults',
  1357. 'clock',
  1358. 'cloudprovider',
  1359. 'common',
  1360. 'docker',
  1361. 'etcd',
  1362. 'hosted',
  1363. 'loadbalancer',
  1364. 'master',
  1365. 'node']
  1366. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  1367. # pylint: disable=too-many-arguments
  1368. def __init__(self, role, filename, local_facts,
  1369. additive_facts_to_overwrite=None,
  1370. openshift_env=None,
  1371. openshift_env_structures=None,
  1372. protected_facts_to_overwrite=None):
  1373. self.changed = False
  1374. self.filename = filename
  1375. if role not in self.known_roles:
  1376. raise OpenShiftFactsUnsupportedRoleError(
  1377. "Role %s is not supported by this module" % role
  1378. )
  1379. self.role = role
  1380. try:
  1381. # ansible-2.1
  1382. # pylint: disable=too-many-function-args
  1383. self.system_facts = ansible_facts(module, ['hardware', 'network', 'virtual', 'facter'])
  1384. except TypeError:
  1385. # ansible-1.9.x,ansible-2.0.x
  1386. self.system_facts = ansible_facts(module)
  1387. self.facts = self.generate_facts(local_facts,
  1388. additive_facts_to_overwrite,
  1389. openshift_env,
  1390. openshift_env_structures,
  1391. protected_facts_to_overwrite)
  1392. def generate_facts(self,
  1393. local_facts,
  1394. additive_facts_to_overwrite,
  1395. openshift_env,
  1396. openshift_env_structures,
  1397. protected_facts_to_overwrite):
  1398. """ Generate facts
  1399. Args:
  1400. local_facts (dict): local_facts for overriding generated defaults
  1401. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1402. '.' notation ex: ['master.named_certificates']
  1403. openshift_env (dict): openshift_env facts for overriding generated defaults
  1404. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1405. '.' notation ex: ['master.master_count']
  1406. Returns:
  1407. dict: The generated facts
  1408. """
  1409. local_facts = self.init_local_facts(local_facts,
  1410. additive_facts_to_overwrite,
  1411. openshift_env,
  1412. openshift_env_structures,
  1413. protected_facts_to_overwrite)
  1414. roles = local_facts.keys()
  1415. if 'common' in local_facts and 'deployment_type' in local_facts['common']:
  1416. deployment_type = local_facts['common']['deployment_type']
  1417. else:
  1418. deployment_type = 'origin'
  1419. defaults = self.get_defaults(roles, deployment_type)
  1420. provider_facts = self.init_provider_facts()
  1421. facts = apply_provider_facts(defaults, provider_facts)
  1422. facts = merge_facts(facts,
  1423. local_facts,
  1424. additive_facts_to_overwrite,
  1425. protected_facts_to_overwrite)
  1426. facts = migrate_oauth_template_facts(facts)
  1427. facts['current_config'] = get_current_config(facts)
  1428. facts = set_url_facts_if_unset(facts)
  1429. facts = set_project_cfg_facts_if_unset(facts)
  1430. facts = set_flannel_facts_if_unset(facts)
  1431. facts = set_nuage_facts_if_unset(facts)
  1432. facts = set_node_schedulability(facts)
  1433. facts = set_selectors(facts)
  1434. facts = set_metrics_facts_if_unset(facts)
  1435. facts = set_identity_providers_if_unset(facts)
  1436. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  1437. facts = set_deployment_facts_if_unset(facts)
  1438. facts = set_container_facts_if_unset(facts)
  1439. facts = build_kubelet_args(facts)
  1440. facts = build_controller_args(facts)
  1441. facts = build_api_server_args(facts)
  1442. facts = set_version_facts_if_unset(facts)
  1443. facts = set_dnsmasq_facts_if_unset(facts)
  1444. facts = set_manageiq_facts_if_unset(facts)
  1445. facts = set_aggregate_facts(facts)
  1446. facts = set_etcd_facts_if_unset(facts)
  1447. facts = set_proxy_facts(facts)
  1448. if not safe_get_bool(facts['common']['is_containerized']):
  1449. facts = set_installed_variant_rpm_facts(facts)
  1450. return dict(openshift=facts)
  1451. def get_defaults(self, roles, deployment_type):
  1452. """ Get default fact values
  1453. Args:
  1454. roles (list): list of roles for this host
  1455. Returns:
  1456. dict: The generated default facts
  1457. """
  1458. defaults = {}
  1459. ip_addr = self.system_facts['default_ipv4']['address']
  1460. exit_code, output, _ = module.run_command(['hostname', '-f'])
  1461. hostname_f = output.strip() if exit_code == 0 else ''
  1462. hostname_values = [hostname_f, self.system_facts['nodename'],
  1463. self.system_facts['fqdn']]
  1464. hostname = choose_hostname(hostname_values, ip_addr)
  1465. defaults['common'] = dict(use_openshift_sdn=True, ip=ip_addr,
  1466. public_ip=ip_addr,
  1467. deployment_type=deployment_type,
  1468. hostname=hostname,
  1469. public_hostname=hostname,
  1470. portal_net='172.30.0.0/16',
  1471. client_binary='oc', admin_binary='oadm',
  1472. dns_domain='cluster.local',
  1473. install_examples=True,
  1474. debug_level=2)
  1475. if 'master' in roles:
  1476. scheduler_predicates = [
  1477. {"name": "MatchNodeSelector"},
  1478. {"name": "PodFitsResources"},
  1479. {"name": "PodFitsPorts"},
  1480. {"name": "NoDiskConflict"},
  1481. {"name": "Region", "argument": {"serviceAffinity" : {"labels" : ["region"]}}}
  1482. ]
  1483. scheduler_priorities = [
  1484. {"name": "LeastRequestedPriority", "weight": 1},
  1485. {"name": "SelectorSpreadPriority", "weight": 1},
  1486. {"name": "Zone", "weight" : 2, "argument": {"serviceAntiAffinity" : {"label": "zone"}}}
  1487. ]
  1488. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  1489. controllers_port='8444',
  1490. console_use_ssl=True,
  1491. console_path='/console',
  1492. console_port='8443', etcd_use_ssl=True,
  1493. etcd_hosts='', etcd_port='4001',
  1494. portal_net='172.30.0.0/16',
  1495. embedded_etcd=True, embedded_kube=True,
  1496. embedded_dns=True,
  1497. bind_addr='0.0.0.0',
  1498. session_max_seconds=3600,
  1499. session_name='ssn',
  1500. session_secrets_file='',
  1501. access_token_max_seconds=86400,
  1502. auth_token_max_seconds=500,
  1503. oauth_grant_method='auto',
  1504. scheduler_predicates=scheduler_predicates,
  1505. scheduler_priorities=scheduler_priorities,
  1506. dynamic_provisioning_enabled=True,
  1507. max_requests_inflight=500)
  1508. if 'node' in roles:
  1509. defaults['node'] = dict(labels={}, annotations={},
  1510. iptables_sync_period='5s',
  1511. local_quota_per_fsgroup="",
  1512. set_node_ip=False)
  1513. if 'docker' in roles:
  1514. docker = dict(disable_push_dockerhub=False,
  1515. hosted_registry_insecure=True,
  1516. options='--log-driver=json-file --log-opt max-size=50m')
  1517. version_info = get_docker_version_info()
  1518. if version_info is not None:
  1519. docker['api_version'] = version_info['api_version']
  1520. docker['version'] = version_info['version']
  1521. docker['gte_1_10'] = LooseVersion(version_info['version']) >= LooseVersion('1.10')
  1522. defaults['docker'] = docker
  1523. if 'clock' in roles:
  1524. exit_code, _, _ = module.run_command(['rpm', '-q', 'chrony'])
  1525. if exit_code == 0:
  1526. chrony_installed = True
  1527. else:
  1528. chrony_installed = False
  1529. defaults['clock'] = dict(
  1530. enabled=True,
  1531. chrony_installed=chrony_installed)
  1532. if 'cloudprovider' in roles:
  1533. defaults['cloudprovider'] = dict(kind=None)
  1534. if 'hosted' in roles or self.role == 'hosted':
  1535. defaults['hosted'] = dict(
  1536. metrics=dict(
  1537. deploy=False,
  1538. duration=7,
  1539. resolution='10s',
  1540. storage=dict(
  1541. kind=None,
  1542. volume=dict(
  1543. name='metrics',
  1544. size='10Gi'
  1545. ),
  1546. nfs=dict(
  1547. directory='/exports',
  1548. options='*(rw,root_squash)'),
  1549. openstack=dict(
  1550. filesystem='ext4',
  1551. volumeID='123'),
  1552. host=None,
  1553. access_modes=['ReadWriteMany'],
  1554. create_pv=True
  1555. )
  1556. ),
  1557. registry=dict(
  1558. storage=dict(
  1559. kind=None,
  1560. volume=dict(
  1561. name='registry',
  1562. size='5Gi'
  1563. ),
  1564. nfs=dict(
  1565. directory='/exports',
  1566. options='*(rw,root_squash)'),
  1567. host=None,
  1568. access_modes=['ReadWriteMany'],
  1569. create_pv=True
  1570. )
  1571. ),
  1572. router=dict()
  1573. )
  1574. if 'loadbalancer' in roles:
  1575. loadbalancer = dict(frontend_port='8443',
  1576. default_maxconn='20000',
  1577. global_maxconn='20000',
  1578. limit_nofile='100000')
  1579. defaults['loadbalancer'] = loadbalancer
  1580. return defaults
  1581. def guess_host_provider(self):
  1582. """ Guess the host provider
  1583. Returns:
  1584. dict: The generated default facts for the detected provider
  1585. """
  1586. # TODO: cloud provider facts should probably be submitted upstream
  1587. product_name = self.system_facts['product_name']
  1588. product_version = self.system_facts['product_version']
  1589. virt_type = self.system_facts['virtualization_type']
  1590. virt_role = self.system_facts['virtualization_role']
  1591. provider = None
  1592. metadata = None
  1593. # TODO: this is not exposed through module_utils/facts.py in ansible,
  1594. # need to create PR for ansible to expose it
  1595. bios_vendor = get_file_content(
  1596. '/sys/devices/virtual/dmi/id/bios_vendor'
  1597. )
  1598. if bios_vendor == 'Google':
  1599. provider = 'gce'
  1600. metadata_url = ('http://metadata.google.internal/'
  1601. 'computeMetadata/v1/?recursive=true')
  1602. headers = {'Metadata-Flavor': 'Google'}
  1603. metadata = get_provider_metadata(metadata_url, True, headers,
  1604. True)
  1605. # Filter sshKeys and serviceAccounts from gce metadata
  1606. if metadata:
  1607. metadata['project']['attributes'].pop('sshKeys', None)
  1608. metadata['instance'].pop('serviceAccounts', None)
  1609. elif (virt_type == 'xen' and virt_role == 'guest'
  1610. and re.match(r'.*\.amazon$', product_version)):
  1611. provider = 'aws'
  1612. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1613. metadata = get_provider_metadata(metadata_url)
  1614. elif re.search(r'OpenStack', product_name):
  1615. provider = 'openstack'
  1616. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1617. 'meta_data.json')
  1618. metadata = get_provider_metadata(metadata_url, True, None,
  1619. True)
  1620. if metadata:
  1621. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1622. metadata['ec2_compat'] = get_provider_metadata(
  1623. ec2_compat_url
  1624. )
  1625. # disable pylint maybe-no-member because overloaded use of
  1626. # the module name causes pylint to not detect that results
  1627. # is an array or hash
  1628. # pylint: disable=maybe-no-member
  1629. # Filter public_keys and random_seed from openstack metadata
  1630. metadata.pop('public_keys', None)
  1631. metadata.pop('random_seed', None)
  1632. if not metadata['ec2_compat']:
  1633. metadata = None
  1634. return dict(name=provider, metadata=metadata)
  1635. def init_provider_facts(self):
  1636. """ Initialize the provider facts
  1637. Returns:
  1638. dict: The normalized provider facts
  1639. """
  1640. provider_info = self.guess_host_provider()
  1641. provider_facts = normalize_provider_facts(
  1642. provider_info.get('name'),
  1643. provider_info.get('metadata')
  1644. )
  1645. return provider_facts
  1646. @staticmethod
  1647. def split_openshift_env_fact_keys(openshift_env_fact, openshift_env_structures):
  1648. """ Split openshift_env facts based on openshift_env structures.
  1649. Args:
  1650. openshift_env_fact (string): the openshift_env fact to split
  1651. ex: 'openshift_cloudprovider_openstack_auth_url'
  1652. openshift_env_structures (list): a list of structures to determine fact keys
  1653. ex: ['openshift.cloudprovider.openstack.*']
  1654. Returns:
  1655. list: a list of keys that represent the fact
  1656. ex: ['openshift', 'cloudprovider', 'openstack', 'auth_url']
  1657. """
  1658. # By default, we'll split an openshift_env fact by underscores.
  1659. fact_keys = openshift_env_fact.split('_')
  1660. # Determine if any of the provided variable structures match the fact.
  1661. matching_structure = None
  1662. if openshift_env_structures != None:
  1663. for structure in openshift_env_structures:
  1664. if re.match(structure, openshift_env_fact):
  1665. matching_structure = structure
  1666. # Fact didn't match any variable structures so return the default fact keys.
  1667. if matching_structure is None:
  1668. return fact_keys
  1669. final_keys = []
  1670. structure_keys = matching_structure.split('.')
  1671. for structure_key in structure_keys:
  1672. # Matched current key. Add to final keys.
  1673. if structure_key == fact_keys[structure_keys.index(structure_key)]:
  1674. final_keys.append(structure_key)
  1675. # Wildcard means we will be taking everything from here to the end of the fact.
  1676. elif structure_key == '*':
  1677. final_keys.append('_'.join(fact_keys[structure_keys.index(structure_key):]))
  1678. # Shouldn't have gotten here, return the fact keys.
  1679. else:
  1680. return fact_keys
  1681. return final_keys
  1682. # Disabling too-many-branches and too-many-locals.
  1683. # This should be cleaned up as a TODO item.
  1684. #pylint: disable=too-many-branches, too-many-locals
  1685. def init_local_facts(self, facts=None,
  1686. additive_facts_to_overwrite=None,
  1687. openshift_env=None,
  1688. openshift_env_structures=None,
  1689. protected_facts_to_overwrite=None):
  1690. """ Initialize the local facts
  1691. Args:
  1692. facts (dict): local facts to set
  1693. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1694. '.' notation ex: ['master.named_certificates']
  1695. openshift_env (dict): openshift env facts to set
  1696. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1697. '.' notation ex: ['master.master_count']
  1698. Returns:
  1699. dict: The result of merging the provided facts with existing
  1700. local facts
  1701. """
  1702. changed = False
  1703. facts_to_set = dict()
  1704. if facts is not None:
  1705. facts_to_set[self.role] = facts
  1706. if openshift_env != {} and openshift_env != None:
  1707. for fact, value in openshift_env.iteritems():
  1708. oo_env_facts = dict()
  1709. current_level = oo_env_facts
  1710. keys = self.split_openshift_env_fact_keys(fact, openshift_env_structures)[1:]
  1711. if len(keys) > 0 and keys[0] != self.role:
  1712. continue
  1713. for key in keys:
  1714. if key == keys[-1]:
  1715. current_level[key] = value
  1716. elif key not in current_level:
  1717. current_level[key] = dict()
  1718. current_level = current_level[key]
  1719. facts_to_set = merge_facts(orig=facts_to_set,
  1720. new=oo_env_facts,
  1721. additive_facts_to_overwrite=[],
  1722. protected_facts_to_overwrite=[])
  1723. local_facts = get_local_facts_from_file(self.filename)
  1724. migrated_facts = migrate_local_facts(local_facts)
  1725. new_local_facts = merge_facts(migrated_facts,
  1726. facts_to_set,
  1727. additive_facts_to_overwrite,
  1728. protected_facts_to_overwrite)
  1729. if 'docker' in new_local_facts:
  1730. # remove duplicate and empty strings from registry lists
  1731. for cat in ['additional', 'blocked', 'insecure']:
  1732. key = '{0}_registries'.format(cat)
  1733. if key in new_local_facts['docker']:
  1734. val = new_local_facts['docker'][key]
  1735. if isinstance(val, basestring):
  1736. val = [x.strip() for x in val.split(',')]
  1737. new_local_facts['docker'][key] = list(set(val) - set(['']))
  1738. # Convert legacy log_options comma sep string to a list if present:
  1739. if 'log_options' in new_local_facts['docker'] and \
  1740. isinstance(new_local_facts['docker']['log_options'], basestring):
  1741. new_local_facts['docker']['log_options'] = new_local_facts['docker']['log_options'].split(',')
  1742. new_local_facts = self.remove_empty_facts(new_local_facts)
  1743. if new_local_facts != local_facts:
  1744. self.validate_local_facts(new_local_facts)
  1745. changed = True
  1746. if not module.check_mode:
  1747. save_local_facts(self.filename, new_local_facts)
  1748. self.changed = changed
  1749. return new_local_facts
  1750. def remove_empty_facts(self, facts=None):
  1751. """ Remove empty facts
  1752. Args:
  1753. facts (dict): facts to clean
  1754. """
  1755. facts_to_remove = []
  1756. for fact, value in facts.iteritems():
  1757. if isinstance(facts[fact], dict):
  1758. facts[fact] = self.remove_empty_facts(facts[fact])
  1759. else:
  1760. if value == "" or value == [""] or value is None:
  1761. facts_to_remove.append(fact)
  1762. for fact in facts_to_remove:
  1763. del facts[fact]
  1764. return facts
  1765. def validate_local_facts(self, facts=None):
  1766. """ Validate local facts
  1767. Args:
  1768. facts (dict): local facts to validate
  1769. """
  1770. invalid_facts = dict()
  1771. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1772. if invalid_facts:
  1773. msg = 'Invalid facts detected:\n'
  1774. for key in invalid_facts.keys():
  1775. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  1776. module.fail_json(msg=msg,
  1777. changed=self.changed)
  1778. # disabling pylint errors for line-too-long since we're dealing
  1779. # with best effort reduction of error messages here.
  1780. # disabling errors for too-many-branches since we require checking
  1781. # many conditions.
  1782. # pylint: disable=line-too-long, too-many-branches
  1783. @staticmethod
  1784. def validate_master_facts(facts, invalid_facts):
  1785. """ Validate master facts
  1786. Args:
  1787. facts (dict): local facts to validate
  1788. invalid_facts (dict): collected invalid_facts
  1789. Returns:
  1790. dict: Invalid facts
  1791. """
  1792. if 'master' in facts:
  1793. # openshift.master.session_auth_secrets
  1794. if 'session_auth_secrets' in facts['master']:
  1795. session_auth_secrets = facts['master']['session_auth_secrets']
  1796. if not issubclass(type(session_auth_secrets), list):
  1797. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  1798. elif 'session_encryption_secrets' not in facts['master']:
  1799. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  1800. 'if openshift_master_session_auth_secrets is provided.')
  1801. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  1802. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  1803. 'openshift_master_session_encryption_secrets must be '
  1804. 'equal length.')
  1805. else:
  1806. for secret in session_auth_secrets:
  1807. if len(secret) < 32:
  1808. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  1809. 'Secrets must be at least 32 characters in length.')
  1810. # openshift.master.session_encryption_secrets
  1811. if 'session_encryption_secrets' in facts['master']:
  1812. session_encryption_secrets = facts['master']['session_encryption_secrets']
  1813. if not issubclass(type(session_encryption_secrets), list):
  1814. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  1815. elif 'session_auth_secrets' not in facts['master']:
  1816. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  1817. 'set if openshift_master_session_encryption_secrets '
  1818. 'is provided.')
  1819. else:
  1820. for secret in session_encryption_secrets:
  1821. if len(secret) not in [16, 24, 32]:
  1822. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  1823. 'Secrets must be 16, 24, or 32 characters in length.')
  1824. return invalid_facts
  1825. def main():
  1826. """ main """
  1827. # disabling pylint errors for global-variable-undefined and invalid-name
  1828. # for 'global module' usage, since it is required to use ansible_facts
  1829. # pylint: disable=global-variable-undefined, invalid-name
  1830. global module
  1831. module = AnsibleModule(
  1832. argument_spec=dict(
  1833. role=dict(default='common', required=False,
  1834. choices=OpenShiftFacts.known_roles),
  1835. local_facts=dict(default=None, type='dict', required=False),
  1836. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1837. openshift_env=dict(default={}, type='dict', required=False),
  1838. openshift_env_structures=dict(default=[], type='list', required=False),
  1839. protected_facts_to_overwrite=dict(default=[], type='list', required=False),
  1840. ),
  1841. supports_check_mode=True,
  1842. add_file_common_args=True,
  1843. )
  1844. role = module.params['role']
  1845. local_facts = module.params['local_facts']
  1846. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite']
  1847. openshift_env = module.params['openshift_env']
  1848. openshift_env_structures = module.params['openshift_env_structures']
  1849. protected_facts_to_overwrite = module.params['protected_facts_to_overwrite']
  1850. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1851. openshift_facts = OpenShiftFacts(role,
  1852. fact_file,
  1853. local_facts,
  1854. additive_facts_to_overwrite,
  1855. openshift_env,
  1856. openshift_env_structures,
  1857. protected_facts_to_overwrite)
  1858. file_params = module.params.copy()
  1859. file_params['path'] = fact_file
  1860. file_args = module.load_file_common_arguments(file_params)
  1861. changed = module.set_fs_attributes_if_different(file_args,
  1862. openshift_facts.changed)
  1863. return module.exit_json(changed=changed,
  1864. ansible_facts=openshift_facts.facts)
  1865. # ignore pylint errors related to the module_utils import
  1866. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  1867. # import module snippets
  1868. from ansible.module_utils.basic import *
  1869. from ansible.module_utils.facts import *
  1870. from ansible.module_utils.urls import *
  1871. if __name__ == '__main__':
  1872. main()