def _SetIPAddresses(self):
     show_cmd = os_utils.OpenStackCLICommand(self, 'server', 'show',
                                             self.name)
     stdout, _, _ = show_cmd.Issue()
     server_dict = json.loads(stdout)
     self.ip_address = self._GetNetworkIPAddress(server_dict,
                                                 self.network_name)
     self.internal_ip = self.ip_address
     if self.floating_ip_pool_name:
         self.floating_ip = self._AllocateFloatingIP()
         self.internal_ip = self.ip_address
         self.ip_address = self.floating_ip.floating_ip_address
 def _DeleteSSHPublicKey(self):
   """Deletes SSH public key used for the VM."""
   with self._lock:
     if self.zone in self.deleted_keypair_set:
       return
     cmd = os_utils.OpenStackCLICommand(self, 'keypair', 'delete',
                                        self.key_name)
     del cmd.flags['format']  # keypair delete does not support json output
     cmd.Issue()
     self.deleted_keypair_set.add(self.zone)
     if self.zone in self.uploaded_keypair_set:
       self.uploaded_keypair_set.remove(self.zone)
 def _UploadSSHPublicKey(self):
   """Uploads SSH public key to the VM's region."""
   with self._lock:
     if self.zone in self.uploaded_keypair_set:
       return
     cmd = os_utils.OpenStackCLICommand(self, 'keypair', 'create',
                                        self.key_name)
     cmd.flags['public-key'] = self.ssh_public_key
     cmd.IssueRetryable()
     self.uploaded_keypair_set.add(self.zone)
     if self.zone in self.deleted_keypair_set:
       self.deleted_keypair_set.remove(self.zone)
    def _Exists(self):
        if self.id is None:
            return False

        show_cmd = os_utils.OpenStackCLICommand(self, 'server', 'show',
                                                self.id)
        stdout, _, _ = show_cmd.Issue(suppress_warning=True)
        try:
            resp = json.loads(stdout)
            return resp
        except ValueError:
            return False
Ejemplo n.º 5
0
 def _DetachVolume(self):
     if self.id is None:
         raise errors.Error('Cannot detach remote volume %s' % self.name)
     if self.attached_vm_id is None:
         raise errors.Error(
             'Cannot detach remote volume from a non-existing VM.')
     cmd = os_utils.OpenStackCLICommand(self, 'server', 'remove', 'volume',
                                        self.attached_vm_id, self.id)
     del cmd.flags['format']
     _, stderr, _ = cmd.Issue()
     if stderr:
         raise errors.Error(stderr)
 def _CheckFloatingIPNetworkExists(self):
   cmd = os_utils.OpenStackCLICommand(self, 'ip', 'floating', 'pool', 'list')
   stdout, stderr, _ = cmd.Issue()
   resp = json.loads(stdout)
   for flip_pool in resp:
     if flip_pool['Name'] == self.floating_ip_pool_name:
       break
   else:
     raise errors.Config.InvalidValue(' '.join(
         ('Floating IP pool %s could not be found.'
          % self.floating_ip_pool_name,
          'For valid floating IP pools run '
          '"openstack ip floating pool list".',)))
Ejemplo n.º 7
0
 def _allocate(self, vm):
   cmd = utils.OpenStackCLICommand(vm, OSC_IP_CMD, OSC_FLOATING_SUBCMD,
                                   'create', self.ip_pool_name)
   stdout, stderr, _ = cmd.Issue()
   if stderr.strip():  # Strip spaces
     raise errors.Config.InvalidValue(
         'Could not allocate a floating ip from the pool "%s".'
         % self.ip_pool_name)
   floating_ip_dict = json.loads(stdout)
   # Convert OSC format to nova's format
   floating_ip_dict['ip'] = floating_ip_dict['floating_ip_address']
   del floating_ip_dict['floating_ip_address']
   return floating_ip_dict
Ejemplo n.º 8
0
 def _WaitForVolumeAttachment(self, vm):
     if self.id is None:
         return
     cmd = os_utils.OpenStackCLICommand(self, 'volume', 'show', self.id)
     stdout, stderr, _ = cmd.Issue()
     if stderr:
         raise errors.Error(stderr)
     resp = json.loads(stdout)
     attachments = resp['attachments']
     self.device_path = self._GetDeviceFromAttachment(attachments)
     msg = 'Remote volume %s has been attached to %s.' % (self.name,
                                                          vm.name)
     logging.info(msg)
Ejemplo n.º 9
0
 def _AttachVolume(self, vm):
     if self.id is None:
         raise errors.Error('Cannot attach remote volume %s' % self.name)
     if vm.id is None:
         msg = 'Cannot attach remote volume %s to non-existing %s VM' % (
             self.name, vm.name)
         raise errors.Error(msg)
     cmd = os_utils.OpenStackCLICommand(self, 'server', 'add', 'volume',
                                        vm.id, self.id)
     del cmd.flags['format']
     _, stderr, _ = cmd.Issue()
     if stderr:
         raise errors.Error(stderr)
 def _CheckCanaryCommand(self):
   if OpenStackVirtualMachine.command_works:  # fast path
     return
   with self._lock:
     if OpenStackVirtualMachine.command_works:
       return
     logging.info('Testing OpenStack CLI command is installed and working')
     cmd = os_utils.OpenStackCLICommand(self, 'image', 'list')
     stdout, stderr, _ = cmd.Issue()
     if stderr:
       raise errors.Config.InvalidValue(
           'OpenStack CLI test command failed. Please make sure the OpenStack '
           'CLI client is installed and properly configured')
     OpenStackVirtualMachine.command_works = True
 def _allocate(self, vm):
     cmd = utils.OpenStackCLICommand(vm, OSC_FLOATING_IP_CMD, 'create',
                                     self.floating_network_id)
     stdout, stderr, _ = cmd.Issue()
     if stderr.strip():  # Strip spaces
         raise errors.Config.InvalidValue(
             'Could not allocate a floating ip from the floating network "%s".'
             % self.floating_network_id)
     floating_ip_dict = json.loads(stdout)
     # Extract subset of returned keys
     floating_ip_obj = OpenStackFloatingIP(
         floating_ip_address=floating_ip_dict['floating_ip_address'],
         floating_network_id=floating_ip_dict['floating_network_id'],
         id=floating_ip_dict['id'])
     return floating_ip_obj
Ejemplo n.º 12
0
 def _WaitForVolumeDeletion(self):
     if self.id is None:
         return
     cmd = os_utils.OpenStackCLICommand(self, 'volume', 'show', self.id)
     stdout, stderr, _ = cmd.Issue(suppress_warning=True)
     if stderr.strip():
         return  # Volume could not be found, inferred that has been deleted.
     resp = json.loads(stdout)
     if resp['status'] in (
             'building',
             'available',
             'in-use',
             'deleting',
     ):
         msg = (
             'Volume %s has not yet been deleted. Retrying to check status.'
             % self.id)
         raise errors.Resource.RetryableDeletionError(msg)
Ejemplo n.º 13
0
  def _get_or_create(self, vm):
    list_cmd = utils.OpenStackCLICommand(vm, OSC_FLOATING_IP_CMD, 'list')
    stdout, stderr, _ = list_cmd.Issue()
    if stderr:
      raise errors.Error(stderr)
    floating_ip_dict_list = json.loads(stdout)

    for floating_ip_dict in floating_ip_dict_list:
      if (floating_ip_dict['Floating Network'] == self.floating_network_id
              and floating_ip_dict['Port'] is None):
        # Due to inconsistent output, we need to convert the keys
        floating_ip_obj = OpenStackFloatingIP(
            floating_ip_address=floating_ip_dict['Floating IP Address'],
            floating_network_id=floating_ip_dict['Floating Network'],
            id=floating_ip_dict['ID']
        )
        return floating_ip_obj
    return self._allocate(vm)
  def _GetCreateCommand(self):
    cmd = os_utils.OpenStackCLICommand(self, 'server', 'create', self.name)
    cmd.flags['flavor'] = self.machine_type
    cmd.flags['security-group'] = self.group_id
    cmd.flags['key-name'] = self.key_name
    cmd.flags['availability-zone'] = self.zone
    cmd.flags['nic'] = 'net-id=%s' % self.network_name
    cmd.flags['wait'] = True
    if FLAGS.openstack_config_drive:
      cmd.flags['config-drive'] = 'True'

    hints = self._GetSchedulerHints()
    if hints:
      cmd.flags['hint'] = hints

    if FLAGS.openstack_boot_from_volume:
      cmd.flags['volume'] = self.boot_volume_id
    else:
      cmd.flags['image'] = self.image

    return cmd
Ejemplo n.º 15
0
  def AllowICMP(self, vm, icmp_type=-1, icmp_code=-1):
    """Creates a Security Group Rule on the Firewall to allow/disallow
    ICMP traffic.

    Args:
      vm: The BaseVirtualMachine object to allow ICMP traffic to.
      icmp_type: ICMP type to allow. If none given then allows all types.
      icmp_code: ICMP code to allow. If none given then allows all codes.
    """
    if vm.is_static:
      return

    sec_group_rule = (ICMP, icmp_type, icmp_code, vm.group_id)
    with self._lock:
      if sec_group_rule in self.sec_group_rules_set:
        return
      cmd = utils.OpenStackCLICommand(vm, OSC_SEC_GROUP_RULE_CMD, 'create',
                                      vm.group_id)
      cmd.flags['dst-port'] = str(icmp_type)
      cmd.flags['proto'] = ICMP
      cmd.Issue(suppress_warning=True)
      self.sec_group_rules_set.add(sec_group_rule)
Ejemplo n.º 16
0
def DeleteVolume(resource, volume_id):
    """Deletes a remote (Cinder) block volume."""
    vol_cmd = os_utils.OpenStackCLICommand(resource, 'volume', 'delete',
                                           volume_id)
    del vol_cmd.flags['format']  # volume delete does not support json output
    vol_cmd.Issue()
 def _DeleteInstance(self):
   cmd = os_utils.OpenStackCLICommand(self, 'server', 'delete', self.id)
   del cmd.flags['format']  # delete does not support json output
   cmd.flags['wait'] = True
   cmd.Issue(suppress_warning=True)
 def _CheckNetworkExists(self):
   cmd = os_utils.OpenStackCLICommand(self, 'network', 'show',
                                      self.network_name)
   err_msg = VALIDATION_ERROR_MESSAGE.format('Network', self.network_name)
   self._IssueCommandCheck(cmd, err_msg)
Ejemplo n.º 19
0
 def testCommonFlagsWithoutOptionalFlags(self):
     rack_resource = OpenStackResource()
     cmd = utils.OpenStackCLICommand(rack_resource, 'image', 'list')
     self.assertEqual(
         cmd._GetCommand(),
         ['path/openstack', 'image', 'list', '--format', 'json'])
 def _CheckFlavor(self):
   """Tries to get flavor, if found continues execution otherwise aborts."""
   cmd = os_utils.OpenStackCLICommand(self, 'flavor', 'show',
                                      self.machine_type)
   err_msg = VALIDATION_ERROR_MESSAGE.format('Machine type', self.machine_type)
   self._IssueCommandCheck(cmd, err_msg)
 def _CheckImage(self):
   """Tries to get image, if found continues execution otherwise aborts."""
   cmd = os_utils.OpenStackCLICommand(self, 'image', 'show', self.image)
   err_msg = VALIDATION_ERROR_MESSAGE.format('Image', self.image)
   self._IssueCommandCheck(cmd, err_msg)
Ejemplo n.º 22
0
 def testIssueCommandRaiseOnFailureFalse(self, mock_cmd):
     rack_resource = OpenStackResource()
     cmd = utils.OpenStackCLICommand(rack_resource)
     cmd.Issue(raise_on_failure=False)
     mock_cmd.assert_called_with(['path/openstack', '--format', 'json'],
                                 raise_on_failure=False)