cluster 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. #!/usr/bin/env python
  2. # vim: expandtab:tabstop=4:shiftwidth=4
  3. import argparse
  4. import ConfigParser
  5. import sys
  6. import os
  7. class Cluster(object):
  8. """
  9. Control and Configuration Interface for OpenShift Clusters
  10. """
  11. def __init__(self):
  12. # setup ansible ssh environment
  13. if 'ANSIBLE_SSH_ARGS' not in os.environ:
  14. os.environ['ANSIBLE_SSH_ARGS'] = (
  15. '-o ForwardAgent=yes '
  16. '-o StrictHostKeyChecking=no '
  17. '-o UserKnownHostsFile=/dev/null '
  18. '-o ControlMaster=auto '
  19. '-o ControlPersist=600s '
  20. )
  21. def create(self, args):
  22. """
  23. Create an OpenShift cluster for given provider
  24. :param args: command line arguments provided by user
  25. :return: exit status from run command
  26. """
  27. env = {'cluster_id': args.cluster_id}
  28. playbook = "playbooks/{}/openshift-cluster/launch.yml".format(args.provider)
  29. inventory = self.setup_provider(args.provider)
  30. env['masters'] = args.masters
  31. env['nodes'] = args.nodes
  32. return self.action(args, inventory, env, playbook)
  33. def terminate(self, args):
  34. """
  35. Destroy OpenShift cluster
  36. :param args: command line arguments provided by user
  37. :return: exit status from run command
  38. """
  39. env = {'cluster_id': args.cluster_id}
  40. playbook = "playbooks/{}/openshift-cluster/terminate.yml".format(args.provider)
  41. inventory = self.setup_provider(args.provider)
  42. return self.action(args, inventory, env, playbook)
  43. def list(self, args):
  44. """
  45. List VMs in cluster
  46. :param args: command line arguments provided by user
  47. :return: exit status from run command
  48. """
  49. raise NotImplementedError("ACTION [{}] not implemented".format(sys._getframe().f_code.co_name))
  50. def update(self, args):
  51. """
  52. Update OpenShift across clustered VMs
  53. :param args: command line arguments provided by user
  54. :return: exit status from run command
  55. """
  56. raise NotImplementedError("ACTION [{}] not implemented".format(sys._getframe().f_code.co_name))
  57. def setup_provider(self, provider):
  58. """
  59. Setup ansible playbook environment
  60. :param provider: command line arguments provided by user
  61. :return: path to inventory for given provider
  62. """
  63. config = ConfigParser.ConfigParser()
  64. if 'gce' == provider:
  65. config.readfp(open('inventory/gce/gce.ini'))
  66. for key in config.options('gce'):
  67. os.environ[key] = config.get('gce', key)
  68. inventory = '-i inventory/gce/gce.py'
  69. elif 'aws' == provider:
  70. config.readfp(open('inventory/aws/ec2.ini'))
  71. for key in config.options('ec2'):
  72. os.environ[key] = config.get('ec2', key)
  73. inventory = '-i inventory/aws/ec2.py'
  74. else:
  75. # this code should never be reached
  76. raise ValueError("invalid PROVIDER {}".format(provider))
  77. return inventory
  78. def action(self, args, inventory, env, playbook):
  79. """
  80. Build ansible-playbook command line and execute
  81. :param args: command line arguments provided by user
  82. :param inventory: derived provider library
  83. :param env: environment variables for kubernetes
  84. :param playbook: ansible playbook to execute
  85. :return: exit status from ansible-playbook command
  86. """
  87. verbose = ''
  88. if args.verbose > 0:
  89. verbose = '-{}'.format('v' * args.verbose)
  90. ansible_env = '-e \'{}\''.format(
  91. ' '.join(['%s=%s' % (key, value) for (key, value) in env.items()])
  92. )
  93. command = 'ansible-playbook {} {} {} {}'.format(
  94. verbose, inventory, ansible_env, playbook
  95. )
  96. if args.verbose > 1:
  97. command = 'time {}'.format(command)
  98. if args.verbose > 0:
  99. sys.stderr.write('RUN [{}]\n'.format(command))
  100. sys.stderr.flush()
  101. return os.system(command)
  102. if __name__ == '__main__':
  103. """
  104. Implemented to support writing unit tests
  105. """
  106. cluster = Cluster()
  107. providers = ['gce', 'aws']
  108. parser = argparse.ArgumentParser(
  109. description='Python wrapper to ensure proper environment for OpenShift ansible playbooks',
  110. )
  111. parser.add_argument('-v', '--verbose', action='count', help='Multiple -v options increase the verbosity')
  112. parser.add_argument('--version', action='version', version='%(prog)s 0.2')
  113. meta_parser = argparse.ArgumentParser(add_help=False)
  114. meta_parser.add_argument('provider', choices=providers, help='provider')
  115. meta_parser.add_argument('cluster_id', help='prefix for cluster VM names')
  116. action_parser = parser.add_subparsers(dest='action', title='actions', description='Choose from valid actions')
  117. create_parser = action_parser.add_parser('create', help='Create a cluster', parents=[meta_parser])
  118. create_parser.add_argument('-m', '--masters', default=1, type=int, help='number of masters to create in cluster')
  119. create_parser.add_argument('-n', '--nodes', default=2, type=int, help='number of nodes to create in cluster')
  120. create_parser.set_defaults(func=cluster.create)
  121. terminate_parser = action_parser.add_parser('terminate', help='Destroy a cluster', parents=[meta_parser])
  122. terminate_parser.add_argument('-f', '--force', action='store_true', help='Destroy cluster without confirmation')
  123. terminate_parser.set_defaults(func=cluster.terminate)
  124. update_parser = action_parser.add_parser('update', help='Update OpenShift across cluster', parents=[meta_parser])
  125. update_parser.add_argument('-f', '--force', action='store_true', help='Update cluster without confirmation')
  126. update_parser.set_defaults(func=cluster.update)
  127. list_parser = action_parser.add_parser('list', help='List VMs in cluster', parents=[meta_parser])
  128. list_parser.set_defaults(func=cluster.list)
  129. args = parser.parse_args()
  130. if 'terminate' == args.action and not args.force:
  131. answer = raw_input("This will destroy the ENTIRE {} environment. Are you sure? [y/N] ".format(args.cluster_id))
  132. if answer not in ['y', 'Y']:
  133. sys.stderr.write('\nACTION [terminate] aborted by user!\n')
  134. exit(1)
  135. if 'update' == args.action and not args.force:
  136. answer = raw_input("This is destructive and could corrupt {} environment. Continue? [y/N] ".format(args.cluster_id))
  137. if answer not in ['y', 'Y']:
  138. sys.stderr.write('\nACTION [update] aborted by user!\n')
  139. exit(1)
  140. status = args.func(args)
  141. if status != 0:
  142. sys.stderr.write("ACTION [{}] failed with exit status {}\n".format(args.action, status))
  143. exit(status)