Exemple #1
0
  def test_random_alphanumeric(self):
    result = utils.get_random_alphanumeric()
    self.assertEquals(len(result), 10)
    for ch in result:
      self.assertTrue(ch.isalnum())

    result = utils.get_random_alphanumeric(15)
    self.assertEqual(len(result), 15)
    for ch in result:
      self.assertTrue(ch.isalnum())
Exemple #2
0
    def test_random_alphanumeric(self):
        result = utils.get_random_alphanumeric()
        self.assertEquals(len(result), 10)
        for ch in result:
            self.assertTrue(ch.isalnum())

        result = utils.get_random_alphanumeric(15)
        self.assertEqual(len(result), 15)
        for ch in result:
            self.assertTrue(ch.isalnum())
  def run_instances(self, parameters, secret):
    """
    Start a new virtual machine deployment using the provided parameters. The
    input parameter set must include an 'infrastructure' parameter which indicates
    the exact cloud environment to use. Value of this parameter will be used to
    instantiate a cloud environment specific agent which knows how to interact
    with the specified cloud platform. The parameters map must also contain a
    'num_vms' parameter which indicates the number of virtual machines that should
    be spawned. In addition to that any parameters required to spawn VMs in the
    specified cloud environment must be included in the parameters map.

    If this InfrastructureManager instance has been created in the blocking mode,
    this method will not return until the VM deployment is complete. Otherwise
    this method will simply kick off the VM deployment process and return
    immediately.

    Args:
      parameters  A parameter map containing the keys 'infrastructure',
                  'num_vms' and any other cloud platform specific
                  parameters. Alternatively one may provide a valid
                  JSON string instead of a dictionary object.
      secret      A previously established secret

    Returns:
      If the secret is valid and all the required parameters are available in
      the input parameter map, this method will return a dictionary containing
      a special 'reservation_id' key. If the secret is invalid or a required
      parameter is missing, this method will return a different map with the
      key 'success' set to False and 'reason' set to a simple error message.

    Raises:
      TypeError   If the inputs are not of the expected types
      ValueError  If the input JSON string (parameters) cannot be parsed properly
    """
    parameters, secret = self.__validate_args(parameters, secret)

    utils.log('Received a request to run instances.')

    if self.secret != secret:
      utils.log('Incoming secret {0} does not match the current secret {1} - '\
                'Rejecting request.'.format(secret, self.secret))
      return self.__generate_response(False, self.REASON_BAD_SECRET)

    for param in self.RUN_INSTANCES_REQUIRED_PARAMS:
      if not utils.has_parameter(param, parameters):
        return self.__generate_response(False, 'no ' + param)

    num_vms = int(parameters[self.PARAM_NUM_VMS])
    if num_vms <= 0:
      utils.log('Invalid VM count: {0}'.format(num_vms))
      return self.__generate_response(False, self.REASON_BAD_VM_COUNT)

    infrastructure = parameters[self.PARAM_INFRASTRUCTURE]
    agent = self.agent_factory.create_agent(infrastructure)
    try:
      agent.assert_required_parameters(parameters, BaseAgent.OPERATION_RUN)
    except AgentConfigurationException as exception:
      return self.__generate_response(False, str(exception))

    reservation_id = utils.get_random_alphanumeric()
    status_info = {
      'success': True,
      'reason': 'received run request',
      'state': self.STATE_PENDING,
      'vm_info': None
    }
    self.reservations.put(reservation_id, status_info)
    utils.log('Generated reservation id {0} for this request.'.format(
      reservation_id))
    try:
      if self.blocking:
        self.__spawn_vms(agent, num_vms, parameters, reservation_id)
      else:
        thread.start_new_thread(self.__spawn_vms,
          (agent, num_vms, parameters, reservation_id))
    except AgentConfigurationException as exception:
      status_info = {
        'success' : False,
        'reason' : str(exception),
        'state' : self.STATE_FAILED,
        'vm_info' : None
      }
      self.reservations.put(reservation_id, status_info)
      utils.log('Updated reservation id {0} with failed status because: {1}' \
        .format(reservation_id, str(exception)))

    utils.log('Successfully started request {0}.'.format(reservation_id))
    return self.__generate_response(True,
      self.REASON_NONE, {'reservation_id': reservation_id})
  def run_instances(self, parameters, secret):
    """
    Start a new virtual machine deployment using the provided parameters. The
    input parameter set must include an 'infrastructure' parameter which indicates
    the exact cloud environment to use. Value of this parameter will be used to
    instantiate a cloud environment specific agent which knows how to interact
    with the specified cloud platform. The parameters map must also contain a
    'num_vms' parameter which indicates the number of virtual machines that should
    be spawned. In addition to that any parameters required to spawn VMs in the
    specified cloud environment must be included in the parameters map.

    If this InfrastructureManager instance has been created in the blocking mode,
    this method will not return until the VM deployment is complete. Otherwise
    this method will simply kick off the VM deployment process and return
    immediately.

    Args:
      parameters  A parameter map containing the keys 'infrastructure',
                  'num_vms' and any other cloud platform specific
                  parameters. Alternatively one may provide a valid
                  JSON string instead of a dictionary object.
      secret      A previously established secret (currently not used)

    Returns:
      If the secret is valid and all the required parameters are available in
      the input parameter map, this method will return a dictionary containing
      a special 'reservation_id' key. If the secret is invalid or a required
      parameter is missing, this method will return a different map with the
      key 'success' set to False and 'reason' set to a simple error message.

    Raises:
      TypeError   If the inputs are not of the expected types
      ValueError  If the input JSON string (parameters) cannot be parsed properly
    """

    utils.log('Received a request to run instances.')

    utils.log('Request parameters are {0}'.format(parameters))
    for param in self.RUN_INSTANCES_REQUIRED_PARAMS:
      if not utils.has_parameter(param, parameters):
        return self.__generate_response(False, 'no ' + param)

    num_vms = int(parameters[self.PARAM_NUM_VMS])
    if num_vms <= 0:
      utils.log('Invalid VM count: {0}'.format(num_vms))
      return self.__generate_response(False, self.REASON_BAD_VM_COUNT)

    infrastructure = parameters[self.PARAM_INFRASTRUCTURE]
    agent = self.agent_factory.create_agent(infrastructure)
    try:
      agent.assert_required_parameters(parameters, BaseAgent.OPERATION_RUN)
    except AgentConfigurationException as exception:
      return self.__generate_response(False, exception.message)

    keyname = parameters[self.PARAM_KEYNAME]
    if keyname is None :
      utils.log('Invalid keyname: '+keyname)
      return self.__generate_response(False, self.REASON_BAD_ARGUMENTS)

    reservation_id = utils.get_random_alphanumeric()
    status_info = {
      'success': True,
      'reason': 'received run request',
      'state': self.STATE_PENDING,
      'vm_info': None
    }
    self.reservations.put(reservation_id, status_info)
    utils.log('Generated reservation id {0} for this request.'.format(
      reservation_id))
    #TODO: We are forcing blocking mode because of how the Google App Engine sandbox environment
    # joins on all threads before returning a response from a request, which effectively makes non-
    # blocking mode the same as blocking mode anyways.
    # (see https://developers.google.com/appengine/docs/python/#Python_The_sandbox)
    if self.blocking or True:
      utils.log('Running spawn_vms in blocking mode')
      self.__spawn_vms(agent, num_vms, parameters, reservation_id)
    else:
      utils.log('Running spawn_vms in non-blocking mode')
      thread.start_new_thread(self.__spawn_vms,
        (agent, num_vms, parameters, reservation_id))
    utils.log('Successfully started request {0}.'.format(reservation_id))
    return self.__generate_response(True,
      self.REASON_NONE, {'reservation_id': reservation_id})
  def terminate_instances(self, parameters, secret):
    """
    Terminate a virtual machine using the provided parameters.
    The input parameter map must contain an 'infrastructure' parameter which
    will be used to instantiate a suitable cloud agent. Any additional
    environment specific parameters should also be available in the same
    map.

    If this InfrastructureManager instance has been created in the blocking mode,
    this method will not return until the VM deployment is complete. Otherwise
    this method simply starts the VM termination process and returns immediately.

    Args:
      parameters  A dictionary of parameters containing the required
                  'infrastructure' parameter and any other platform
                  dependent required parameters. Alternatively one
                  may provide a valid JSON string instead of a dictionary
                  object.
      secret      A previously established secret

    Returns:
      If the secret is valid and all the required parameters are available in
      the input parameter map, this method will return a dictionary containing
      a special 'operation_id' key. If the secret is invalid or a required
      parameter is missing, this method will return a different map with the
      key 'success' set to False and 'reason' set to a simple error message.

    Raises:
      TypeError   If the inputs are not of the expected types
      ValueError  If the input JSON string (parameters) cannot be parsed properly
    """
    parameters, secret = self.__validate_args(parameters, secret)

    if self.secret != secret:
      return self.__generate_response(False, self.REASON_BAD_SECRET)

    for param in self.TERMINATE_INSTANCES_REQUIRED_PARAMS:
      if not utils.has_parameter(param, parameters):
        return self.__generate_response(False, 'no ' + param)

    infrastructure = parameters[self.PARAM_INFRASTRUCTURE]
    agent = self.agent_factory.create_agent(infrastructure)
    try:
      agent.assert_required_parameters(parameters,
        BaseAgent.OPERATION_TERMINATE)
    except AgentConfigurationException as exception:
      return self.__generate_response(False, str(exception))

    operation_id = utils.get_random_alphanumeric()
    status_info = {
      'success': True,
      'reason': 'received kill request',
      'state': self.STATE_PENDING
    }
    self.operation_ids.put(operation_id, status_info)
    utils.log('Generated operation id {0} for this terminate instances '
              'request.'.format(operation_id))

    if self.blocking:
      self.__kill_vms(agent, parameters, operation_id)
    else:
      thread.start_new_thread(self.__kill_vms,
                              (agent, parameters, operation_id))

    utils.log('Successfully started terminate instances request {0}.'.format(
        operation_id))
    return self.__generate_response(True,
      self.REASON_NONE, {'operation_id': operation_id})
  def run_instances(self, parameters, secret):
    """
    Start a new virtual machine deployment using the provided parameters. The
    input parameter set must include an 'infrastructure' parameter which indicates
    the exact cloud environment to use. Value of this parameter will be used to
    instantiate a cloud environment specific agent which knows how to interact
    with the specified cloud platform. The parameters map must also contain a
    'num_vms' parameter which indicates the number of virtual machines that should
    be spawned. In addition to that any parameters required to spawn VMs in the
    specified cloud environment must be included in the parameters map.

    If this InfrastructureManager instance has been created in the blocking mode,
    this method will not return until the VM deployment is complete. Otherwise
    this method will simply kick off the VM deployment process and return
    immediately.

    Args:
      parameters  A parameter map containing the keys 'infrastructure',
                  'num_vms' and any other cloud platform specific
                  parameters. Alternatively one may provide a valid
                  JSON string instead of a dictionary object.
      secret      A previously established secret

    Returns:
      If the secret is valid and all the required parameters are available in
      the input parameter map, this method will return a dictionary containing
      a special 'operation_id' key. If the secret is invalid or a required
      parameter is missing, this method will return a different map with the
      key 'success' set to False and 'reason' set to a simple error message.

    Raises:
      TypeError   If the inputs are not of the expected types
      ValueError  If the input JSON string (parameters) cannot be parsed properly
    """
    parameters, secret = self.__validate_args(parameters, secret)

    utils.log('Received a request to run instances.')

    if self.secret != secret:
      utils.log('Incoming secret {0} does not match the current secret {1} - '\
                'Rejecting request.'.format(secret, self.secret))
      return self.__generate_response(False, self.REASON_BAD_SECRET)

    for param in self.RUN_INSTANCES_REQUIRED_PARAMS:
      if not utils.has_parameter(param, parameters):
        return self.__generate_response(False, 'no ' + param)

    num_vms = int(parameters[self.PARAM_NUM_VMS])
    if num_vms <= 0:
      utils.log('Invalid VM count: {0}'.format(num_vms))
      return self.__generate_response(False, self.REASON_BAD_VM_COUNT)

    infrastructure = parameters[self.PARAM_INFRASTRUCTURE]
    agent = self.agent_factory.create_agent(infrastructure)
    try:
      agent.assert_required_parameters(parameters, BaseAgent.OPERATION_RUN)
    except AgentConfigurationException as exception:
      return self.__generate_response(False, str(exception))

    operation_id = utils.get_random_alphanumeric()
    status_info = {
      'success': True,
      'reason': 'received run request',
      'state': self.STATE_PENDING,
      'vm_info': None
    }
    self.operation_ids.put(operation_id, status_info)
    utils.log('Generated operation id {0} for this run '
              'instances request.'.format(operation_id))
    if self.blocking:
      self.__spawn_vms(agent, num_vms, parameters, operation_id)
    else:
      thread.start_new_thread(self.__spawn_vms,
        (agent, num_vms, parameters, operation_id))

    utils.log('Successfully started run instances request {0}.'.format(
        operation_id))
    return self.__generate_response(True,
      self.REASON_NONE, {'operation_id': operation_id})