cluster 12 KB

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