cluster 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. def get_deployment_type(self, args):
  23. """
  24. Get the deployment_type based on the environment variables and the
  25. command line arguments
  26. :param args: command line arguments provided by the user
  27. :return: string representing the deployment type
  28. """
  29. deployment_type = 'origin'
  30. if args.deployment_type:
  31. deployment_type = args.deployment_type
  32. elif 'OS_DEPLOYMENT_TYPE' in os.environ:
  33. deployment_type = os.environ['OS_DEPLOYMENT_TYPE']
  34. return deployment_type
  35. def create(self, args):
  36. """
  37. Create an OpenShift cluster for given provider
  38. :param args: command line arguments provided by user
  39. :return: exit status from run command
  40. """
  41. env = {'cluster_id': args.cluster_id,
  42. 'deployment_type': self.get_deployment_type(args)}
  43. playbook = "playbooks/{}/openshift-cluster/launch.yml".format(args.provider)
  44. inventory = self.setup_provider(args.provider)
  45. env['num_masters'] = args.masters
  46. env['num_nodes'] = args.nodes
  47. env['num_etcd'] = args.etcd
  48. return self.action(args, inventory, env, playbook)
  49. def terminate(self, args):
  50. """
  51. Destroy OpenShift cluster
  52. :param args: command line arguments provided by user
  53. :return: exit status from run command
  54. """
  55. env = {'cluster_id': args.cluster_id,
  56. 'deployment_type': self.get_deployment_type(args)}
  57. playbook = "playbooks/{}/openshift-cluster/terminate.yml".format(args.provider)
  58. inventory = self.setup_provider(args.provider)
  59. return self.action(args, inventory, env, playbook)
  60. def list(self, args):
  61. """
  62. List VMs in 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/list.yml".format(args.provider)
  69. inventory = self.setup_provider(args.provider)
  70. return self.action(args, inventory, env, playbook)
  71. def config(self, args):
  72. """
  73. Configure or reconfigure OpenShift across clustered VMs
  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/config.yml".format(args.provider)
  80. inventory = self.setup_provider(args.provider)
  81. return self.action(args, inventory, env, playbook)
  82. def update(self, args):
  83. """
  84. Update to latest 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/update.yml".format(args.provider)
  91. inventory = self.setup_provider(args.provider)
  92. return self.action(args, inventory, env, playbook)
  93. def service(self, args):
  94. """
  95. Make the same service call across all nodes in the cluster
  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. 'new_cluster_state': args.state}
  102. playbook = "playbooks/{}/openshift-cluster/service.yml".format(args.provider)
  103. inventory = self.setup_provider(args.provider)
  104. return self.action(args, inventory, env, playbook)
  105. def setup_provider(self, provider):
  106. """
  107. Setup ansible playbook environment
  108. :param provider: command line arguments provided by user
  109. :return: path to inventory for given provider
  110. """
  111. config = ConfigParser.ConfigParser()
  112. if 'gce' == provider:
  113. config.readfp(open('inventory/gce/hosts/gce.ini'))
  114. for key in config.options('gce'):
  115. os.environ[key] = config.get('gce', key)
  116. inventory = '-i inventory/gce/hosts'
  117. elif 'aws' == provider:
  118. config.readfp(open('inventory/aws/hosts/ec2.ini'))
  119. for key in config.options('ec2'):
  120. os.environ[key] = config.get('ec2', key)
  121. inventory = '-i inventory/aws/hosts'
  122. key_vars = ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']
  123. key_missing = [key for key in key_vars if key not in os.environ]
  124. boto_conf_files = ['~/.aws/credentials', '~/.boto']
  125. conf_exists = lambda conf: os.path.isfile(os.path.expanduser(conf))
  126. boto_configs = [ conf for conf in boto_conf_files if conf_exists(conf)]
  127. if len(key_missing) > 0 and len(boto_configs) == 0:
  128. raise ValueError("PROVIDER aws requires {} environment variable(s). See README_AWS.md".format(missing))
  129. elif 'libvirt' == provider:
  130. inventory = '-i inventory/libvirt/hosts'
  131. elif 'openstack' == provider:
  132. inventory = '-i inventory/openstack/hosts'
  133. else:
  134. # this code should never be reached
  135. raise ValueError("invalid PROVIDER {}".format(provider))
  136. return inventory
  137. def action(self, args, inventory, env, playbook):
  138. """
  139. Build ansible-playbook command line and execute
  140. :param args: command line arguments provided by user
  141. :param inventory: derived provider library
  142. :param env: environment variables for kubernetes
  143. :param playbook: ansible playbook to execute
  144. :return: exit status from ansible-playbook command
  145. """
  146. verbose = ''
  147. if args.verbose > 0:
  148. verbose = '-{}'.format('v' * args.verbose)
  149. if args.option:
  150. for opt in args.option:
  151. k, v = opt.split('=', 1)
  152. env['cli_' + k] = v
  153. ansible_env = '-e \'{}\''.format(
  154. ' '.join(['%s=%s' % (key, value) for (key, value) in env.items()])
  155. )
  156. command = 'ansible-playbook {} {} {} {}'.format(
  157. verbose, inventory, ansible_env, playbook
  158. )
  159. if args.profile:
  160. command = 'ANSIBLE_CALLBACK_PLUGINS=ansible-profile/callback_plugins ' + command
  161. if args.verbose > 1:
  162. command = 'time {}'.format(command)
  163. if args.verbose > 0:
  164. sys.stderr.write('RUN [{}]\n'.format(command))
  165. sys.stderr.flush()
  166. return os.system(command)
  167. if __name__ == '__main__':
  168. """
  169. User command to invoke ansible playbooks in a "known" environment
  170. Reads ~/.openshift-ansible for default configuration items
  171. [DEFAULT]
  172. validate_cluster_ids = False
  173. cluster_ids = marketing,sales
  174. providers = gce,aws,libvirt,openstack
  175. """
  176. environment = ConfigParser.SafeConfigParser({
  177. 'cluster_ids': 'marketing,sales',
  178. 'validate_cluster_ids': 'False',
  179. 'providers': 'gce,aws,libvirt,openstack',
  180. })
  181. path = os.path.expanduser("~/.openshift-ansible")
  182. if os.path.isfile(path):
  183. environment.read(path)
  184. cluster = Cluster()
  185. parser = argparse.ArgumentParser(
  186. description='Python wrapper to ensure proper environment for OpenShift ansible playbooks',
  187. )
  188. parser.add_argument('-v', '--verbose', action='count',
  189. help='Multiple -v options increase the verbosity')
  190. parser.add_argument('--version', action='version', version='%(prog)s 0.3')
  191. meta_parser = argparse.ArgumentParser(add_help=False)
  192. providers = environment.get('DEFAULT', 'providers').split(',')
  193. meta_parser.add_argument('provider', choices=providers, help='provider')
  194. if environment.get('DEFAULT', 'validate_cluster_ids').lower() in ("yes", "true", "1"):
  195. meta_parser.add_argument('cluster_id', choices=environment.get('DEFAULT', 'cluster_ids').split(','),
  196. help='prefix for cluster VM names')
  197. else:
  198. meta_parser.add_argument('cluster_id', help='prefix for cluster VM names')
  199. meta_parser.add_argument('-t', '--deployment-type',
  200. choices=['origin', 'online', 'enterprise'],
  201. help='Deployment type. (default: origin)')
  202. meta_parser.add_argument('-o', '--option', action='append',
  203. help='options')
  204. meta_parser.add_argument('-p', '--profile', action='store_true',
  205. help='Enable playbook profiling')
  206. action_parser = parser.add_subparsers(dest='action', title='actions',
  207. description='Choose from valid actions')
  208. create_parser = action_parser.add_parser('create', help='Create a cluster',
  209. parents=[meta_parser])
  210. create_parser.add_argument('-m', '--masters', default=1, type=int,
  211. help='number of masters to create in cluster')
  212. create_parser.add_argument('-n', '--nodes', default=2, type=int,
  213. help='number of nodes to create in cluster')
  214. create_parser.add_argument('-e', '--etcd', default=0, type=int,
  215. help='number of external etcd hosts to create in cluster')
  216. create_parser.set_defaults(func=cluster.create)
  217. config_parser = action_parser.add_parser('config',
  218. help='Configure or reconfigure a cluster',
  219. parents=[meta_parser])
  220. config_parser.set_defaults(func=cluster.config)
  221. terminate_parser = action_parser.add_parser('terminate',
  222. help='Destroy a cluster',
  223. parents=[meta_parser])
  224. terminate_parser.add_argument('-f', '--force', action='store_true',
  225. help='Destroy cluster without confirmation')
  226. terminate_parser.set_defaults(func=cluster.terminate)
  227. update_parser = action_parser.add_parser('update',
  228. help='Update OpenShift across cluster',
  229. parents=[meta_parser])
  230. update_parser.add_argument('-f', '--force', action='store_true',
  231. help='Update cluster without confirmation')
  232. update_parser.set_defaults(func=cluster.update)
  233. list_parser = action_parser.add_parser('list', help='List VMs in cluster',
  234. parents=[meta_parser])
  235. list_parser.set_defaults(func=cluster.list)
  236. service_parser = action_parser.add_parser('service', help='service for openshift across cluster',
  237. parents=[meta_parser])
  238. # choices are the only ones valid for the ansible service module: http://docs.ansible.com/service_module.html
  239. service_parser.add_argument('state', choices=['started', 'stopped', 'restarted', 'reloaded'],
  240. help='make service call across cluster')
  241. service_parser.set_defaults(func=cluster.service)
  242. args = parser.parse_args()
  243. if 'terminate' == args.action and not args.force:
  244. answer = raw_input("This will destroy the ENTIRE {} environment. Are you sure? [y/N] ".format(args.cluster_id))
  245. if answer not in ['y', 'Y']:
  246. sys.stderr.write('\nACTION [terminate] aborted by user!\n')
  247. exit(1)
  248. if 'update' == args.action and not args.force:
  249. answer = raw_input(
  250. "This is destructive and could corrupt {} environment. Continue? [y/N] ".format(args.cluster_id))
  251. if answer not in ['y', 'Y']:
  252. sys.stderr.write('\nACTION [update] aborted by user!\n')
  253. exit(1)
  254. status = 1
  255. try:
  256. status = args.func(args)
  257. if status != 0:
  258. sys.stderr.write("ACTION [{}] failed with exit status {}\n".format(args.action, status))
  259. except Exception, e:
  260. if args.verbose:
  261. traceback.print_exc(file=sys.stderr)
  262. else:
  263. sys.stderr.write("{}\n".format(e))
  264. exit(status)