Set a Physical Device to be used as an LVM Physical Volume

    name
        The device name to initialize.

    kwargs
        Any supported options to pvcreate. See
        :mod:`linux_lvm <salt.modules.linux_lvm>` for more details.
435112
def pv_present(name, **kwargs):
    '''
    
    '''
    ret = {'changes': {},
           'comment': '',
           'name': name,
           'result': True}

    if __salt__['lvm.pvdisplay'](name, quiet=True):
        ret['comment'] = 'Physical Volume {0} already present'.format(name)
    elif __opts__['test']:
        ret['comment'] = 'Physical Volume {0} is set to be created'.format(name)
        ret['result'] = None
        return ret
    else:
        changes = __salt__['lvm.pvcreate'](name, **kwargs)

        if __salt__['lvm.pvdisplay'](name):
            ret['comment'] = 'Created Physical Volume {0}'.format(name)
            ret['changes']['created'] = changes
        else:
            ret['comment'] = 'Failed to create Physical Volume {0}'.format(name)
            ret['result'] = False
    return ret
516959
def set_name(self, new_name):
        

        # change the hostname in the startup-config
        if os.path.isfile(self.startup_config_path):
            try:
                with open(self.startup_config_path, "r+", encoding="utf-8", errors="replace") as f:
                    old_config = f.read()
                    new_config = re.sub(r"^hostname .+$", "hostname " + new_name, old_config, flags=re.MULTILINE)
                    f.seek(0)
                    f.write(new_config)
            except OSError as e:
                raise DynamipsError("Could not amend the configuration {}: {}".format(self.startup_config_path, e))

        # change the hostname in the private-config
        if os.path.isfile(self.private_config_path):
            try:
                with open(self.private_config_path, "r+", encoding="utf-8", errors="replace") as f:
                    old_config = f.read()
                    new_config = old_config.replace(self.name, new_name)
                    f.seek(0)
                    f.write(new_config)
            except OSError as e:
                raise DynamipsError("Could not amend the configuration {}: {}".format(self.private_config_path, e))

        yield from self._hypervisor.send('vm rename "{name}" "{new_name}"'.format(name=self._name, new_name=new_name))
        log.info('Router "{name}" [{id}]: renamed to "{new_name}"'.format(name=self._name, id=self._id, new_name=new_name))
        self._name = new_name
457150
def set_hostname(self, userid, hostname, os_version):
        
        tmp_path = self._pathutils.get_guest_temp_path(userid)
        if not os.path.exists(tmp_path):
            os.makedirs(tmp_path)
        tmp_file = tmp_path + '/hostname.sh'

        lnxdist = self._dist_manager.get_linux_dist(os_version)()
        lines = lnxdist.generate_set_hostname_script(hostname)
        with open(tmp_file, 'w') as f:
            f.writelines(lines)

        requestData = "ChangeVM " + userid + " punchfile " + \
                            tmp_file + " --class x"
        LOG.debug("Punch script to guest %s to set hostname" % userid)

        try:
            self._smtclient._request(requestData)
        except exception.SDKSMTRequestFailed as err:
            msg = ("Failed to punch set_hostname script to userid '%s'. SMT "
                   "error: %s" % (userid, err.format_message()))
            LOG.error(msg)
            raise exception.SDKSMTRequestFailed(err.results, msg)
        finally:
            self._pathutils.clean_temp_folder(tmp_path)
1365854
def name(device, partition, name):
    '''
    
    '''
    _validate_device(device)

    try:
        int(partition)
    except Exception:
        raise CommandExecutionError(
            'Invalid partition passed to partition.name'
        )

    valid = string.ascii_letters + string.digits + ' _-'
    for letter in name:
        if letter not in valid:
            raise CommandExecutionError(
                'Invalid characters passed to partition.name'
            )

    cmd = '''parted -m -s {0} name {1} "'{2}'"'''.format(device, partition, name)
    out = __salt__['cmd.run'](cmd).splitlines()
    return out
618522
def libvlc_vlm_set_enabled(p_instance, psz_name, b_enabled):
    '''
    '''
    f = _Cfunctions.get('libvlc_vlm_set_enabled', None) or \
        _Cfunction('libvlc_vlm_set_enabled', ((1,), (1,), (1,),), None,
                    ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
    return f(p_instance, psz_name, b_enabled)
134772
def attach_volume(name=None, kwargs=None, instance_id=None, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The attach_volume action must be called with -a or --action.'
        )

    if not kwargs:
        kwargs = {}

    if 'instance_id' in kwargs:
        instance_id = kwargs['instance_id']

    if name and not instance_id:
        instance_id = _get_node(name)['instanceId']

    if not name and not instance_id:
        log.error('Either a name or an instance_id is required.')
        return False

    if 'volume_id' not in kwargs:
        log.error('A volume_id is required.')
        return False

    if 'device' not in kwargs:
        log.error('A device is required (ex. /dev/sdb1).')
        return False

    params = {'Action': 'AttachVolume',
              'VolumeId': kwargs['volume_id'],
              'InstanceId': instance_id,
              'Device': kwargs['device']}

    log.debug(params)

    vm_ = get_configured_provider()

    data = salt.utils.cloud.wait_for_ip(
        __attach_vol_to_instance,
        update_args=(params, kwargs, instance_id),
        timeout=config.get_cloud_config_value(
            'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
        interval=config.get_cloud_config_value(
            'wait_for_ip_interval', vm_, __opts__, default=10),
        interval_multiplier=config.get_cloud_config_value(
            'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
    )

    return data
79201
def create_hosting_device_resources(self, context, complementary_id,
                                        tenant_id, mgmt_context, max_hosted):
        """"""
        mgmt_port = None
        if mgmt_context and mgmt_context.get('mgmt_nw_id') and tenant_id:
            # Create port for mgmt interface
            p_spec = {'port': {
                'tenant_id': tenant_id,
                'admin_state_up': True,
                'name': 'mgmt',
                'network_id': mgmt_context['mgmt_nw_id'],
                'mac_address': bc.constants.ATTR_NOT_SPECIFIED,
                'fixed_ips': self._mgmt_subnet_spec(context, mgmt_context),
                'device_id': "",
                # Use device_owner attribute to ensure we can query for these
                # ports even before Nova has set device_id attribute.
                'device_owner': complementary_id}}
            try:
                mgmt_port = self._core_plugin.create_port(context, p_spec)
            except n_exc.NeutronException as e:
                LOG.error('Error %s when creating management port. '
                          'Cleaning up.', e)
                self.delete_hosting_device_resources(
                    context, tenant_id, mgmt_port)
                mgmt_port = None
        # We are setting the 'ports' to an empty list as it is expected by
        # the callee: device_handling_db._create_svc_vm_hosting_devices()
        return {'mgmt_port': mgmt_port, 'ports': []}
820820
def create_a10_device_instance(self, context, a10_device_instance):
        """"""
        LOG.debug("A10DeviceInstancePlugin.create(): a10_device_instance=%s", a10_device_instance)

        config = a10_config.A10Config()
        vthunder_defaults = config.get_vthunder_config()

        imgr = instance_manager.InstanceManager.from_config(config, context)

        dev_instance = common_resources.remove_attributes_not_specified(
            a10_device_instance.get(resources.RESOURCE))

        # Create the instance with specified defaults.
        vthunder_config = vthunder_defaults.copy()
        vthunder_config.update(_convert(dev_instance, _API, _VTHUNDER_CONFIG))
        instance = imgr.create_device_instance(vthunder_config, dev_instance.get("name"))

        db_record = {}
        db_record.update(_convert(vthunder_config, _VTHUNDER_CONFIG, _DB))
        db_record.update(_convert(dev_instance, _API, _DB))
        db_record.update(_convert(instance, _INSTANCE, _DB))

        # If success, return the created DB record
        # Else, raise an exception because that's what we would do anyway
        db_instance = super(A10DeviceInstancePlugin, self).create_a10_device_instance(
            context, {resources.RESOURCE: db_record})

        return _make_api_dict(db_instance)
813995
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'softlayer_hw',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    name = vm_['name']
    hostname = name
    domain = config.get_cloud_config_value(
        'domain', vm_, __opts__, default=None
    )
    if domain is None:
        SaltCloudSystemExit(
            'A domain name is required for the SoftLayer driver.'
        )

    if vm_.get('use_fqdn'):
        name = '.'.join([name, domain])
        vm_['name'] = name

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(name),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', name)
    conn = get_conn(service='SoftLayer_Product_Order')
    kwargs = {
        'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server',
        'quantity': 1,
        'hardware': [{
            'hostname': hostname,
            'domain': domain,
        }],
        # Baremetal Package
        'packageId': 50,
        'prices': [
            # Size Ex: 1921: 2 x 2.0 GHz Core Bare Metal Instance - 2 GB Ram
            {'id': vm_['size']},
            # HDD Ex: 19: 250GB SATA II
            {'id': vm_['hdd']},
            # Image Ex: 13963: CentOS 6.0 - Minimal Install (64 bit)
            {'id': vm_['image']},

            # The following items are currently required
            # Reboot / Remote Console
            {'id': '905'},
            # 1 IP Address
            {'id': '21'},
            # Host Ping Monitoring
            {'id': '55'},
            # Email and Ticket Notifications
            {'id': '57'},
            # Automated Notification Response
            {'id': '58'},
            # Unlimited SSL VPN Users & 1 PPTP VPN User per account
            {'id': '420'},
            # Nessus Vulnerability Assessment & Reporting
            {'id': '418'},
        ],
    }

    optional_products = config.get_cloud_config_value(
        'optional_products', vm_, __opts__, default=[]
    )
    for product in optional_products:
        kwargs['prices'].append({'id': product})

    # Default is 273 (100 Mbps Public & Private Networks)
    port_speed = config.get_cloud_config_value(
        'port_speed', vm_, __opts__, default=273
    )
    kwargs['prices'].append({'id': port_speed})

    # Default is 1800 (0 GB Bandwidth)
    bandwidth = config.get_cloud_config_value(
        'bandwidth', vm_, __opts__, default=1800
    )
    kwargs['prices'].append({'id': bandwidth})

    post_uri = config.get_cloud_config_value(
        'post_uri', vm_, __opts__, default=None
    )
    if post_uri:
        kwargs['prices'].append({'id': post_uri})

    vlan_id = config.get_cloud_config_value(
        'vlan', vm_, __opts__, default=False
    )
    if vlan_id:
        kwargs['primaryNetworkComponent'] = {
            'networkVlan': {
                'id': vlan_id,
            }
        }

    location = get_location(vm_)
    if location:
        kwargs['location'] = location

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(name),
        args={
            'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    try:
        response = conn.placeOrder(kwargs)
        # Leaving the following line in, commented, for easy debugging
        #response = conn.verifyOrder(kwargs)
    except Exception as exc:
        log.error(
            'Error creating %s on SoftLayer\n\n'
            'The following exception was thrown when trying to '
            'run the initial deployment: \n%s', name, exc,
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return False

    def wait_for_ip():
        '''
        Wait for the IP address to become available
        '''
        nodes = list_nodes_full()
        if 'primaryIpAddress' in nodes[hostname]:
            return nodes[hostname]['primaryIpAddress']
        time.sleep(1)
        return False

    ip_address = salt.utils.cloud.wait_for_fun(
        wait_for_ip,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )

    ssh_connect_timeout = config.get_cloud_config_value(
        # 15 minutes
        'ssh_connect_timeout', vm_, __opts__, 900
    )
    if not salt.utils.cloud.wait_for_port(ip_address,
                                         timeout=ssh_connect_timeout):
        raise SaltCloudSystemExit(
            'Failed to authenticate against remote ssh'
        )

    pass_conn = get_conn(service='SoftLayer_Account')
    mask = {
        'virtualGuests': {
            'powerState': '',
            'operatingSystem': {
                'passwords': ''
            },
        },
    }

    def get_passwd():
        '''
        Wait for the password to become available
        '''
        node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
        for node in node_info:
            if node['id'] == response['id'] \
                    and 'passwords' in node['operatingSystem'] \
                    and node['operatingSystem']['passwords']:
                return node['operatingSystem']['passwords'][0]['password']
        time.sleep(5)
        return False

    passwd = salt.utils.cloud.wait_for_fun(
        get_passwd,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )
    response['password'] = passwd
    response['public_ip'] = ip_address

    ssh_username = config.get_cloud_config_value(
        'ssh_username', vm_, __opts__, default='root'
    )

    vm_['ssh_host'] = ip_address
    vm_['password'] = passwd
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update(response)

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(name),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
840853
def set_input_shape_ngpu(self, new_input_shape):
    
    assert self.device_name, "Device name has not been set."

    device_name = self.device_name
    if self.input_shape is None:
      # First time setting the input shape
      self.input_shape = [None] + [int(d) for d in list(new_input_shape)]

    if device_name in self.params_device:
      # There is a copy of weights on this device
      self.__dict__.update(self.params_device[device_name])
      return

    # Stop recursion
    self.params_device[device_name] = {}

    # Initialize weights on this device
    with tf.device(device_name):
      self.set_input_shape(self.input_shape)
      keys_after = self.__dict__.keys()
      if self.params_names is None:
        # Prevent overriding training
        self.params_names = [k for k in keys_after if isinstance(
            self.__dict__[k], tf.Variable)]
      params = {k: self.__dict__[k] for k in self.params_names}
      self.params_device[device_name] = params
1011441
def set_(device, **kwargs):
    '''
    
    '''
    empty = {'block-soft-limit': 0, 'block-hard-limit': 0,
             'file-soft-limit': 0, 'file-hard-limit': 0}

    current = None
    cmd = 'setquota'
    if 'user' in kwargs:
        cmd += ' -u {0} '.format(kwargs['user'])
        parsed = _parse_quota(device, '-u')
        if kwargs['user'] in parsed:
            current = parsed['Users'][kwargs['user']]
        else:
            current = empty
        ret = 'User: {0}'.format(kwargs['user'])

    if 'group' in kwargs:
        if 'user' in kwargs:
            raise SaltInvocationError(
                'Please specify a user or group, not both.'
            )
        cmd += ' -g {0} '.format(kwargs['group'])
        parsed = _parse_quota(device, '-g')
        if kwargs['group'] in parsed:
            current = parsed['Groups'][kwargs['group']]
        else:
            current = empty
        ret = 'Group: {0}'.format(kwargs['group'])

    if not current:
        raise CommandExecutionError('A valid user or group was not found')

    for limit in ('block-soft-limit', 'block-hard-limit',
                  'file-soft-limit', 'file-hard-limit'):
        if limit in kwargs:
            current[limit] = kwargs[limit]

    cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'],
                                        current['block-hard-limit'],
                                        current['file-soft-limit'],
                                        current['file-hard-limit'],
                                        device)

    result = __salt__['cmd.run_all'](cmd, python_shell=False)
    if result['retcode'] != 0:
        raise CommandExecutionError(
            'Unable to set desired quota. Error follows: \n{0}'
            .format(result['stderr'])
        )
    return {ret: current}
604622
def create_lb(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The create_lb function must be called with -f or --function.'
        )

    if not kwargs or 'name' not in kwargs:
        log.error(
            'A name must be specified when creating a health check.'
        )
        return False
    if 'ports' not in kwargs:
        log.error(
            'A port or port-range must be specified for the load-balancer.'
        )
        return False
    if 'region' not in kwargs:
        log.error(
            'A region must be specified for the load-balancer.'
        )
        return False
    if 'members' not in kwargs:
        log.error(
            'A comma-separated list of members must be specified.'
        )
        return False

    name = kwargs['name']
    ports = kwargs['ports']
    ex_region = kwargs['region']
    members = kwargs.get('members').split(',')

    protocol = kwargs.get('protocol', 'tcp')
    algorithm = kwargs.get('algorithm', None)
    ex_healthchecks = kwargs.get('healthchecks', None)

    # pylint: disable=W0511

    conn = get_conn()
    lb_conn = get_lb_conn(conn)

    ex_address = kwargs.get('address', None)
    if ex_address is not None:
        ex_address = __create_orget_address(conn, ex_address, ex_region)

    if ex_healthchecks:
        ex_healthchecks = ex_healthchecks.split(',')

    __utils__['cloud.fire_event'](
        'event',
        'create load_balancer',
        'salt/cloud/loadbalancer/creating',
        args=kwargs,
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    lb = lb_conn.create_balancer(
        name, ports, protocol, algorithm, members,
        ex_region=ex_region, ex_healthchecks=ex_healthchecks,
        ex_address=ex_address
    )

    __utils__['cloud.fire_event'](
        'event',
        'created load_balancer',
        'salt/cloud/loadbalancer/created',
        args=kwargs,
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return _expand_balancer(lb)
708662
def start(name):
    '''
    
    '''
    ret = {}
    cmd = '{0} startvm {1}'.format(vboxcmd(), name)
    ret = salt.modules.cmdmod.run(cmd).splitlines()
    return ret
205862
def create(self, name, **kwargs):
        
        # These arguments are required
        self.required('create', kwargs, ['hostname', 'port',
                      'storage_hostname', 'volume_type_name', 'size'])
        kwargs['name'] = name
        return self.http_post('/nodes', params=kwargs)
669280
def set_device_name(self, newname):
        
        return self.write(request.SetDeviceName(self.seq, *self.prep_str(newname)))
618809
def set_pv_args(name, kwargs=None, session=None, call=None):
    '''
    

    '''
    if call == 'function':
        raise SaltCloudException(
            'This function must be called with -a or --action.'
        )
    if session is None:
        log.debug('New session being created')
        session = _get_session()
    vm = _get_vm(name, session=session)
    try:
        log.debug('Setting PV Args: %s', kwargs['pv_args'])
        session.xenapi.VM.set_PV_args(vm, str(kwargs['pv_args']))
    except KeyError:
        log.error('No pv_args parameter found.')
        return False
    except XenAPI.Failure:
        log.info('Setting PV Args failed.')
        return False
    return True
507060
def attach_disk(name=None, kwargs=None, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The attach_disk action must be called with -a or --action.'
        )

    if not name:
        log.error(
            'Must specify an instance name.'
        )
        return False
    if not kwargs or 'disk_name' not in kwargs:
        log.error(
            'Must specify a disk_name to attach.'
        )
        return False

    node_name = name
    disk_name = kwargs['disk_name']
    mode = kwargs.get('mode', 'READ_WRITE').upper()
    boot = kwargs.get('boot', False)
    auto_delete = kwargs.get('auto_delete', False)
    if boot and boot.lower() in ['true', 'yes', 'enabled']:
        boot = True
    else:
        boot = False

    if mode not in ['READ_WRITE', 'READ_ONLY']:
        log.error(
            'Mode must be either READ_ONLY or (default) READ_WRITE.'
        )
        return False

    conn = get_conn()
    node = conn.ex_get_node(node_name)
    disk = conn.ex_get_volume(disk_name)

    __utils__['cloud.fire_event'](
        'event',
        'attach disk',
        'salt/cloud/disk/attaching',
        args={
            'name': node_name,
            'disk_name': disk_name,
            'mode': mode,
            'boot': boot,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    result = conn.attach_volume(node, disk, ex_mode=mode, ex_boot=boot,
                                ex_auto_delete=auto_delete)

    __utils__['cloud.fire_event'](
        'event',
        'attached disk',
        'salt/cloud/disk/attached',
        args={
            'name': node_name,
            'disk_name': disk_name,
            'mode': mode,
            'boot': boot,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return result