cluster 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #!/usr/bin/env python2
  2. # vim: expandtab:tabstop=4:shiftwidth=4
  3. import argparse
  4. import ConfigParser
  5. import os
  6. import sys
  7. import traceback
  8. class Cluster(object):
  9. """
  10. Provide Command, Control and Configuration (c3) Interface for OpenShift Clusters
  11. """
  12. def __init__(self):
  13. # setup ansible ssh environment
  14. if 'ANSIBLE_SSH_ARGS' not in os.environ:
  15. os.environ['ANSIBLE_SSH_ARGS'] = (
  16. '-o ForwardAgent=yes '
  17. '-o StrictHostKeyChecking=no '
  18. '-o UserKnownHostsFile=/dev/null '
  19. '-o ControlMaster=auto '
  20. '-o ControlPersist=600s '
  21. )
  22. # Because of `UserKnownHostsFile=/dev/null`
  23. # our `.ssh/known_hosts` file most probably misses the ssh host public keys
  24. # of our servers.
  25. # In that case, ansible serializes the execution of ansible modules
  26. # because we might be interactively prompted to accept the ssh host public keys.
  27. # Because of `StrictHostKeyChecking=no` we know that we won't be prompted
  28. # So, we don't want our modules execution to be serialized.
  29. os.environ['ANSIBLE_HOST_KEY_CHECKING'] = 'False'
  30. # TODO: A more secure way to proceed would consist in dynamically
  31. # retrieving the ssh host public keys from the IaaS interface
  32. def get_deployment_type(self, args):
  33. """
  34. Get the deployment_type based on the environment variables and the
  35. command line arguments
  36. :param args: command line arguments provided by the user
  37. :return: string representing the deployment type
  38. """
  39. deployment_type = 'origin'
  40. if args.deployment_type:
  41. deployment_type = args.deployment_type
  42. elif 'OS_DEPLOYMENT_TYPE' in os.environ:
  43. deployment_type = os.environ['OS_DEPLOYMENT_TYPE']
  44. return deployment_type
  45. def create(self, args):
  46. """
  47. Create an OpenShift cluster for given provider
  48. :param args: command line arguments provided by user
  49. :return: exit status from run command
  50. """
  51. env = {'cluster_id': args.cluster_id,
  52. 'deployment_type': self.get_deployment_type(args)}
  53. playbook = "playbooks/{}/openshift-cluster/launch.yml".format(args.provider)
  54. inventory = self.setup_provider(args.provider)
  55. env['num_masters'] = args.masters
  56. env['num_nodes'] = args.nodes
  57. env['num_infra'] = args.infra
  58. env['num_etcd'] = args.etcd
  59. return self.action(args, inventory, env, playbook)
  60. def terminate(self, args):
  61. """
  62. Destroy OpenShift cluster
  63. :param args: command line arguments provided by user
  64. :return: exit status from run command
  65. """
  66. env = {'cluster_id': args.cluster_id,
  67. 'deployment_type': self.get_deployment_type(args)}
  68. playbook = "playbooks/{}/openshift-cluster/terminate.yml".format(args.provider)
  69. inventory = self.setup_provider(args.provider)
  70. return self.action(args, inventory, env, playbook)
  71. def list(self, args):
  72. """
  73. List VMs in cluster
  74. :param args: command line arguments provided by user
  75. :return: exit status from run command
  76. """
  77. env = {'cluster_id': args.cluster_id,
  78. 'deployment_type': self.get_deployment_type(args)}
  79. playbook = "playbooks/{}/openshift-cluster/list.yml".format(args.provider)
  80. inventory = self.setup_provider(args.provider)
  81. return self.action(args, inventory, env, playbook)
  82. def config(self, args):
  83. """
  84. Configure or reconfigure OpenShift across clustered VMs
  85. :param args: command line arguments provided by user
  86. :return: exit status from run command
  87. """
  88. env = {'cluster_id': args.cluster_id,
  89. 'deployment_type': self.get_deployment_type(args)}
  90. playbook = "playbooks/{}/openshift-cluster/config.yml".format(args.provider)
  91. inventory = self.setup_provider(args.provider)
  92. return self.action(args, inventory, env, playbook)
  93. def update(self, args):
  94. """
  95. Update to latest OpenShift across clustered VMs
  96. :param args: command line arguments provided by user
  97. :return: exit status from run command
  98. """
  99. env = {'cluster_id': args.cluster_id,
  100. 'deployment_type': self.get_deployment_type(args)}
  101. playbook = "playbooks/{}/openshift-cluster/update.yml".format(args.provider)
  102. inventory = self.setup_provider(args.provider)
  103. return self.action(args, inventory, env, playbook)
  104. def service(self, args):
  105. """
  106. Make the same service call across all nodes in the cluster
  107. :param args: command line arguments provided by user
  108. :return: exit status from run command
  109. """
  110. env = {'cluster_id': args.cluster_id,
  111. 'deployment_type': self.get_deployment_type(args),
  112. 'new_cluster_state': args.state}
  113. playbook = "playbooks/{}/openshift-cluster/service.yml".format(args.provider)
  114. inventory = self.setup_provider(args.provider)
  115. return self.action(args, inventory, env, playbook)
  116. def setup_provider(self, provider):
  117. """
  118. Setup ansible playbook environment
  119. :param provider: command line arguments provided by user
  120. :return: path to inventory for given provider
  121. """
  122. config = ConfigParser.ConfigParser()
  123. if 'gce' == provider:
  124. config.readfp(open('inventory/gce/hosts/gce.ini'))
  125. for key in config.options('gce'):
  126. os.environ[key] = config.get('gce', key)
  127. inventory = '-i inventory/gce/hosts'
  128. elif 'aws' == provider:
  129. config.readfp(open('inventory/aws/hosts/ec2.ini'))
  130. for key in config.options('ec2'):
  131. os.environ[key] = config.get('ec2', key)
  132. inventory = '-i inventory/aws/hosts'
  133. key_vars = ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']
  134. key_missing = [key for key in key_vars if key not in os.environ]
  135. boto_conf_files = ['~/.aws/credentials', '~/.boto']
  136. conf_exists = lambda conf: os.path.isfile(os.path.expanduser(conf))
  137. boto_configs = [conf for conf in boto_conf_files if conf_exists(conf)]
  138. if len(key_missing) > 0 and len(boto_configs) == 0:
  139. raise ValueError("PROVIDER aws requires {} environment variable(s). See README_AWS.md".format(missing))
  140. elif 'libvirt' == provider:
  141. inventory = '-i inventory/libvirt/hosts'
  142. elif 'openstack' == provider:
  143. inventory = '-i inventory/openstack/hosts'
  144. else:
  145. # this code should never be reached
  146. raise ValueError("invalid PROVIDER {}".format(provider))
  147. return inventory
  148. def action(self, args, inventory, env, playbook):
  149. """
  150. Build ansible-playbook command line and execute
  151. :param args: command line arguments provided by user
  152. :param inventory: derived provider library
  153. :param env: environment variables for kubernetes
  154. :param playbook: ansible playbook to execute
  155. :return: exit status from ansible-playbook command
  156. """
  157. verbose = ''
  158. if args.verbose > 0:
  159. verbose = '-{}'.format('v' * args.verbose)
  160. if args.option:
  161. for opt in args.option:
  162. k, v = opt.split('=', 1)
  163. env['cli_' + k] = v
  164. ansible_env = '-e \'{}\''.format(
  165. ' '.join(['%s=%s' % (key, value) for (key, value) in env.items()])
  166. )
  167. command = 'ansible-playbook {} {} {} {}'.format(
  168. verbose, inventory, ansible_env, playbook
  169. )
  170. if args.profile:
  171. command = 'ANSIBLE_CALLBACK_PLUGINS=ansible-profile/callback_plugins ' + command
  172. if args.verbose > 1:
  173. command = 'time {}'.format(command)
  174. if args.verbose > 0:
  175. sys.stderr.write('RUN [{}]\n'.format(command))
  176. sys.stderr.flush()
  177. return os.system(command)
  178. if __name__ == '__main__':
  179. """
  180. User command to invoke ansible playbooks in a "known" environment
  181. Reads ~/.openshift-ansible for default configuration items
  182. [DEFAULT]
  183. validate_cluster_ids = False
  184. cluster_ids = marketing,sales
  185. providers = gce,aws,libvirt,openstack
  186. """
  187. environment = ConfigParser.SafeConfigParser({
  188. 'cluster_ids': 'marketing,sales',
  189. 'validate_cluster_ids': 'False',
  190. 'providers': 'gce,aws,libvirt,openstack',
  191. })
  192. path = os.path.expanduser("~/.openshift-ansible")
  193. if os.path.isfile(path):
  194. environment.read(path)
  195. cluster = Cluster()
  196. parser = argparse.ArgumentParser(
  197. description='Python wrapper to ensure proper environment for OpenShift ansible playbooks',
  198. )
  199. parser.add_argument('-v', '--verbose', action='count',
  200. help='Multiple -v options increase the verbosity')
  201. parser.add_argument('--version', action='version', version='%(prog)s 0.3')
  202. meta_parser = argparse.ArgumentParser(add_help=False)
  203. providers = environment.get('DEFAULT', 'providers').split(',')
  204. meta_parser.add_argument('provider', choices=providers, help='provider')
  205. if environment.get('DEFAULT', 'validate_cluster_ids').lower() in ("yes", "true", "1"):
  206. meta_parser.add_argument('cluster_id', choices=environment.get('DEFAULT', 'cluster_ids').split(','),
  207. help='prefix for cluster VM names')
  208. else:
  209. meta_parser.add_argument('cluster_id', help='prefix for cluster VM names')
  210. meta_parser.add_argument('-t', '--deployment-type',
  211. choices=['origin', 'online', 'enterprise'],
  212. help='Deployment type. (default: origin)')
  213. meta_parser.add_argument('-T', '--product-type',
  214. choices=['openshift' 'atomic-enterprise'],
  215. help='Product type. (default: openshift)')
  216. meta_parser.add_argument('-o', '--option', action='append',
  217. help='options')
  218. meta_parser.add_argument('-p', '--profile', action='store_true',
  219. help='Enable playbook profiling')
  220. action_parser = parser.add_subparsers(dest='action', title='actions',
  221. description='Choose from valid actions')
  222. create_parser = action_parser.add_parser('create', help='Create a cluster',
  223. parents=[meta_parser])
  224. create_parser.add_argument('-m', '--masters', default=1, type=int,
  225. help='number of masters to create in cluster')
  226. create_parser.add_argument('-n', '--nodes', default=2, type=int,
  227. help='number of nodes to create in cluster')
  228. create_parser.add_argument('-i', '--infra', default=1, type=int,
  229. help='number of infra nodes to create in cluster')
  230. create_parser.add_argument('-e', '--etcd', default=0, type=int,
  231. help='number of external etcd hosts to create in cluster')
  232. create_parser.set_defaults(func=cluster.create)
  233. config_parser = action_parser.add_parser('config',
  234. help='Configure or reconfigure a cluster',
  235. parents=[meta_parser])
  236. config_parser.set_defaults(func=cluster.config)
  237. terminate_parser = action_parser.add_parser('terminate',
  238. help='Destroy a cluster',
  239. parents=[meta_parser])
  240. terminate_parser.add_argument('-f', '--force', action='store_true',
  241. help='Destroy cluster without confirmation')
  242. terminate_parser.set_defaults(func=cluster.terminate)
  243. update_parser = action_parser.add_parser('update',
  244. help='Update OpenShift across cluster',
  245. parents=[meta_parser])
  246. update_parser.add_argument('-f', '--force', action='store_true',
  247. help='Update cluster without confirmation')
  248. update_parser.set_defaults(func=cluster.update)
  249. list_parser = action_parser.add_parser('list', help='List VMs in cluster',
  250. parents=[meta_parser])
  251. list_parser.set_defaults(func=cluster.list)
  252. service_parser = action_parser.add_parser('service', help='service for openshift across cluster',
  253. parents=[meta_parser])
  254. # choices are the only ones valid for the ansible service module: http://docs.ansible.com/service_module.html
  255. service_parser.add_argument('state', choices=['started', 'stopped', 'restarted', 'reloaded'],
  256. help='make service call across cluster')
  257. service_parser.set_defaults(func=cluster.service)
  258. args = parser.parse_args()
  259. if 'terminate' == args.action and not args.force:
  260. answer = raw_input("This will destroy the ENTIRE {} environment. Are you sure? [y/N] ".format(args.cluster_id))
  261. if answer not in ['y', 'Y']:
  262. sys.stderr.write('\nACTION [terminate] aborted by user!\n')
  263. exit(1)
  264. if 'update' == args.action and not args.force:
  265. answer = raw_input(
  266. "This is destructive and could corrupt {} environment. Continue? [y/N] ".format(args.cluster_id))
  267. if answer not in ['y', 'Y']:
  268. sys.stderr.write('\nACTION [update] aborted by user!\n')
  269. exit(1)
  270. status = 1
  271. try:
  272. status = args.func(args)
  273. if status != 0:
  274. sys.stderr.write("ACTION [{}] failed with exit status {}\n".format(args.action, status))
  275. except Exception, e:
  276. if args.verbose:
  277. traceback.print_exc(file=sys.stderr)
  278. else:
  279. sys.stderr.write("{}\n".format(e))
  280. exit(status)