Sanatize novaclient network parameters
432670
def _sanatize_network_params(self, kwargs):
        '''
        
        '''
        params = [
            'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
            'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
            'priority', 'project_id', 'vlan_start', 'vpn_start'
        ]

        for variable in six.iterkeys(kwargs):  # iterate over a copy, we might delete some
            if variable not in params:
                del kwargs[variable]
        return kwargs
1361351
def sanitize(self):
        
        name = self[self._KEYS.NAME]

        aliases = self.get_aliases(includename=False)
        if name not in aliases:
            # Assign the first source to alias, if not available assign us.
            if self._KEYS.SOURCES in self:
                self.add_quantity(self._KEYS.ALIAS, name, '1')
                if self._KEYS.ALIAS not in self:
                    source = self.add_self_source()
                    self.add_quantity(self._KEYS.ALIAS, name, source)
            else:
                source = self.add_self_source()
                self.add_quantity(self._KEYS.ALIAS, name, source)

        if self._KEYS.ALIAS in self:
            self[self._KEYS.ALIAS].sort(
                key=lambda key: alias_priority(name, key[QUANTITY.VALUE]))
        else:
            self._log.error(
                'There should be at least one alias for `{}`.'.format(name))

        if self._KEYS.PHOTOMETRY in self:
            self[self._KEYS.PHOTOMETRY].sort(
                key=lambda x: ((float(x[PHOTOMETRY.TIME]) if
                                isinstance(x[PHOTOMETRY.TIME],
                                           (basestring, float, int))
                                else min([float(y) for y in
                                          x[PHOTOMETRY.TIME]])) if
                               PHOTOMETRY.TIME in x else 0.0,
                               x[PHOTOMETRY.BAND] if PHOTOMETRY.BAND in
                               x else '',
                               float(x[PHOTOMETRY.MAGNITUDE]) if
                               PHOTOMETRY.MAGNITUDE in x else ''))

        if (self._KEYS.SPECTRA in self and list(
                filter(None, [
                    SPECTRUM.TIME in x for x in self[self._KEYS.SPECTRA]
                ]))):
            self[self._KEYS.SPECTRA].sort(
                key=lambda x: (float(x[SPECTRUM.TIME]) if
                               SPECTRUM.TIME in x else 0.0,
                               x[SPECTRUM.FILENAME] if
                               SPECTRUM.FILENAME in x else '')
            )

        if self._KEYS.SOURCES in self:
            # Remove orphan sources
            source_aliases = [
                x[SOURCE.ALIAS] for x in self[self._KEYS.SOURCES]
            ]
            # Sources with the `PRIVATE` attribute are always retained
            source_list = [
                x[SOURCE.ALIAS] for x in self[self._KEYS.SOURCES]
                if SOURCE.PRIVATE in x
            ]
            for key in self:
                # if self._KEYS.get_key_by_name(key).no_source:
                if (key in [
                        self._KEYS.NAME, self._KEYS.SCHEMA, self._KEYS.SOURCES,
                        self._KEYS.ERRORS
                ]):
                    continue
                for item in self[key]:
                    source_list += item[item._KEYS.SOURCE].split(',')
            new_src_list = sorted(
                list(set(source_aliases).intersection(source_list)))
            new_sources = []
            for source in self[self._KEYS.SOURCES]:
                if source[SOURCE.ALIAS] in new_src_list:
                    new_sources.append(source)
                else:
                    self._log.info('Removing orphaned source from `{}`.'
                                   .format(name))

            if not new_sources:
                del self[self._KEYS.SOURCES]

            self[self._KEYS.SOURCES] = new_sources
1192012
def nova_services_up(self):
        
        required = set(['nova-conductor', 'nova-cert', 'nova-scheduler',
                       'nova-compute'])
        try:
            services = self._nclient.services.list()
        # There are several individual Nova client exceptions but they have
        # no other common base than Exception, hence the long list.
        except Exception as e:
            LOG.error('Failure determining running Nova services: %s', e)
            return False
        return not bool(required.difference(
            [service.binary for service in services
             if service.status == 'enabled' and service.state == 'up']))
733063
def ensure_local_net(
        network_name: str = DOCKER_STARCRAFT_NETWORK,
        subnet_cidr: str = SUBNET_CIDR
) -> None:
    
    logger.info(f"checking whether docker has network {network_name}")
    ipam_pool = docker.types.IPAMPool(subnet=subnet_cidr)
    ipam_config = docker.types.IPAMConfig(pool_configs=[ipam_pool])
    networks = docker_client.networks.list(names=DOCKER_STARCRAFT_NETWORK)
    output = networks[0].short_id if networks else None
    if not output:
        logger.info("network not found, creating ...")
        output = docker_client.networks.create(DOCKER_STARCRAFT_NETWORK, ipam=ipam_config).short_id
    logger.debug(f"docker network id: {output}")
9048
def cli(env, identifier):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)

    secgroup = mgr.get_securitygroup(identifier)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', secgroup['id']])
    table.add_row(['name', secgroup.get('name') or formatting.blank()])
    table.add_row(['description',
                   secgroup.get('description') or formatting.blank()])

    rule_table = formatting.Table(['id', 'remoteIp', 'remoteGroupId',
                                   'direction', 'ethertype', 'portRangeMin',
                                   'portRangeMax', 'protocol'])
    for rule in secgroup.get('rules', []):
        rg_id = rule.get('remoteGroup', {}).get('id') or formatting.blank()
        port_min = rule.get('portRangeMin')
        port_max = rule.get('portRangeMax')
        if port_min is None:
            port_min = formatting.blank()
        if port_max is None:
            port_max = formatting.blank()
        rule_table.add_row([rule['id'],
                            rule.get('remoteIp') or formatting.blank(),
                            rule.get('remoteGroupId', rg_id),
                            rule['direction'],
                            rule.get('ethertype') or formatting.blank(),
                            port_min,
                            port_max,
                            rule.get('protocol') or formatting.blank()])

    table.add_row(['rules', rule_table])

    vsi_table = formatting.Table(['id', 'hostname', 'interface', 'ipAddress'])

    for binding in secgroup.get('networkComponentBindings', []):
        try:
            vsi = binding['networkComponent']['guest']
            vsi_id = vsi['id']
            hostname = vsi['hostname']
            interface = ('PRIVATE' if binding['networkComponent']['port'] == 0
                         else 'PUBLIC')
            ip_address = (vsi['primaryBackendIpAddress']
                          if binding['networkComponent']['port'] == 0
                          else vsi['primaryIpAddress'])
        except KeyError:
            vsi_id = "N/A"
            hostname = "Not enough permission to view"
            interface = "N/A"
            ip_address = "N/A"
        vsi_table.add_row([vsi_id, hostname, interface, ip_address])

    table.add_row(['servers', vsi_table])

    env.fout(table)
702056
def cli(env, identifier, no_vs, no_hardware):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)

    vlan_id = helpers.resolve_id(mgr.resolve_vlan_ids, identifier, 'VLAN')
    vlan = mgr.get_vlan(vlan_id)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', vlan['id']])
    table.add_row(['number', vlan['vlanNumber']])
    table.add_row(['datacenter',
                   vlan['primaryRouter']['datacenter']['longName']])
    table.add_row(['primary_router',
                   vlan['primaryRouter']['fullyQualifiedDomainName']])
    table.add_row(['firewall',
                   'Yes' if vlan['firewallInterfaces'] else 'No'])
    subnets = []
    for subnet in vlan.get('subnets', []):
        subnet_table = formatting.KeyValueTable(['name', 'value'])
        subnet_table.align['name'] = 'r'
        subnet_table.align['value'] = 'l'
        subnet_table.add_row(['id', subnet['id']])
        subnet_table.add_row(['identifier', subnet['networkIdentifier']])
        subnet_table.add_row(['netmask', subnet['netmask']])
        subnet_table.add_row(['gateway', subnet.get('gateway', '-')])
        subnet_table.add_row(['type', subnet['subnetType']])
        subnet_table.add_row(['usable ips',
                              subnet['usableIpAddressCount']])
        subnets.append(subnet_table)

    table.add_row(['subnets', subnets])

    server_columns = ['hostname', 'domain', 'public_ip', 'private_ip']

    if not no_vs:
        if vlan.get('virtualGuests'):
            vs_table = formatting.KeyValueTable(server_columns)
            for vsi in vlan['virtualGuests']:
                vs_table.add_row([vsi.get('hostname'),
                                  vsi.get('domain'),
                                  vsi.get('primaryIpAddress'),
                                  vsi.get('primaryBackendIpAddress')])
            table.add_row(['vs', vs_table])
        else:
            table.add_row(['vs', 'none'])

    if not no_hardware:
        if vlan.get('hardware'):
            hw_table = formatting.Table(server_columns)
            for hardware in vlan['hardware']:
                hw_table.add_row([hardware.get('hostname'),
                                  hardware.get('domain'),
                                  hardware.get('primaryIpAddress'),
                                  hardware.get('primaryBackendIpAddress')])
            table.add_row(['hardware', hw_table])
        else:
            table.add_row(['hardware', 'none'])

    env.fout(table)
1059308
function sanitize(config) {
  const configs = [].concat(config).map((conf) => {
    const result = merge({}, conf);
    delete result.progress;
    delete result.reporter;
    delete result.watchStdin;

    // TODO: remove the need for this
    for (const property of ['entry', 'output']) {
      const target = result[property];
      if (target && Object.keys(target).length === 0) {
        delete result[property];
      }
    }

    return result;
  });

  // if we always return an array, every compilation will be a MultiCompiler
  return configs.length > 1 ? configs : configs[0];
}
392947
def _unsafe_update_server(self, disabled=False):
        """"""
        id = self.network.id
        net = model.Network.from_neutron(self.network)
        if id not in _networks:
            if disabled:
                return
            _networks[id] = net
            _networks[id].create()
        elif disabled:
            _networks[id].delete()
            del _networks[id]
        else:
            _networks[id].update(net)
            _networks[id] = net
235952
def _delete_vdev_info(self, vdev):
        """"""
        vdev = vdev.lower()
        network_config_file_name = self._get_network_file()
        device = self._get_device_name(vdev)
        cmd = '\n'.join(("num=$(sed -n '/auto %s/=' %s)" % (device,
                                                    network_config_file_name),
                        "dns=$(awk 'NR==(\"\'$num\'\"+6)&&"
                        "/dns-nameservers/' %s)" %
                                                    network_config_file_name,
                        "if [[ -n $dns ]]; then",
                        "  sed -i '/auto %s/,+6d' %s" % (device,
                                                    network_config_file_name),
                        "else",
                        "  sed -i '/auto %s/,+5d' %s" % (device,
                                                    network_config_file_name),
                        "fi"))
        return cmd
503222
def system(name, **kwargs):
    '''
    

    '''
    ret = {
        'name': name,
        'changes': {},
        'result': True,
        'comment': 'Global network settings are up to date.',
    }
    apply_net_settings = False
    kwargs['test'] = __opts__['test']
    # Build global network settings
    try:
        old = __salt__['ip.get_network_settings']()
        new = __salt__['ip.build_network_settings'](**kwargs)
        if __opts__['test']:
            if old == new:
                return ret
            if not old and new:
                ret['result'] = None
                ret['comment'] = 'Global network settings are set to be added.'
                return ret
            elif old != new:
                diff = difflib.unified_diff(old, new, lineterm='')
                ret['result'] = None
                ret['comment'] = 'Global network settings are set to be ' \
                                 'updated:\n{0}'.format('\n'.join(diff))
                return ret
        if not old and new:
            apply_net_settings = True
            ret['changes']['network_settings'] = 'Added global network settings.'
        elif old != new:
            diff = difflib.unified_diff(old, new, lineterm='')
            apply_net_settings = True
            ret['changes']['network_settings'] = '\n'.join(diff)
    except AttributeError as error:
        ret['result'] = False
        ret['comment'] = six.text_type(error)
        return ret
    except KeyError as error:
        ret['result'] = False
        ret['comment'] = six.text_type(error)
        return ret

    # Apply global network settings
    if apply_net_settings:
        try:
            __salt__['ip.apply_network_settings'](**kwargs)
        except AttributeError as error:
            ret['result'] = False
            ret['comment'] = six.text_type(error)
            return ret

    return ret
869154
function buildNetworkAcl(name) {
  const cfName = `${name}NetworkAcl`;

  return {
    [cfName]: {
      Type: 'AWS::EC2::NetworkAcl',
      Properties: {
        Tags: [
          {
            Key: 'Name',
            Value: {
              'Fn::Join': [
                '-',
                [
                  {
                    Ref: 'AWS::StackName',
                  },
                  name.toLowerCase(),
                ],
              ],
            },
          },
        ],
        VpcId: {
          Ref: 'VPC',
        },
      },
    },
  };
}
1345993
function normalizeConnectArgs(args)
{
	if( typeof args[0]==='object' && args[0]!==null )
		return args[0]
	else if( typeof args[0]==='string' && !(Number(args[0]) >= 0) )
		return {path: args[0]}
	var options= {port: args[0]}
	if( typeof args[1]==='string' )
		options.host= args[1]
	return options
}
819175
def _modify_eni_properties(eni_id, properties=None, vm_=None):
    '''
    
    '''
    if not isinstance(properties, dict):
        raise SaltCloudException(
            'ENI properties must be a dictionary'
        )

    params = {'Action': 'ModifyNetworkInterfaceAttribute',
              'NetworkInterfaceId': eni_id}
    for k, v in six.iteritems(properties):
        params[k] = v

    result = aws.query(params,
                       return_root=True,
                       location=get_location(vm_),
                       provider=get_provider(),
                       opts=__opts__,
                       sigver='4')

    if isinstance(result, dict) and result.get('error'):
        raise SaltCloudException(
            'Could not change interface <{0}> attributes <\'{1}\'>'.format(
                eni_id, properties
            )
        )
    else:
        return result
64455
def net_query(name: str) -> Constants:
    '''
    '''

    for net_params in networks:
        if name in (net_params.name, net_params.shortname,):
            return net_params

    raise UnsupportedNetwork
539402
def validate_client_parameters(cmd, namespace):
    
    n = namespace

    def get_config_value(section, key, default):
        return cmd.cli_ctx.config.get(section, key, default)

    if hasattr(n, 'auth_mode'):
        auth_mode = n.auth_mode or get_config_value('storage', 'auth_mode', None)
        del n.auth_mode
        if not n.account_name:
            n.account_name = get_config_value('storage', 'account', None)
        if auth_mode == 'login':
            n.token_credential = _create_token_credential(cmd.cli_ctx)

            # give warning if there are account key args being ignored
            account_key_args = [n.account_key and "--account-key", n.sas_token and "--sas-token",
                                n.connection_string and "--connection-string"]
            account_key_args = [arg for arg in account_key_args if arg]

            if account_key_args:
                from knack.log import get_logger

                logger = get_logger(__name__)
                logger.warning('In "login" auth mode, the following arguments are ignored: %s',
                               ' ,'.join(account_key_args))
            return

    if not n.connection_string:
        n.connection_string = get_config_value('storage', 'connection_string', None)

    # if connection string supplied or in environment variables, extract account key and name
    if n.connection_string:
        conn_dict = validate_key_value_pairs(n.connection_string)
        n.account_name = conn_dict.get('AccountName')
        n.account_key = conn_dict.get('AccountKey')
        if not n.account_name or not n.account_key:
            from knack.util import CLIError
            raise CLIError('Connection-string: %s, is malformed. Some shell environments require the '
                           'connection string to be surrounded by quotes.' % n.connection_string)

    # otherwise, simply try to retrieve the remaining variables from environment variables
    if not n.account_name:
        n.account_name = get_config_value('storage', 'account', None)
    if not n.account_key:
        n.account_key = get_config_value('storage', 'key', None)
    if not n.sas_token:
        n.sas_token = get_config_value('storage', 'sas_token', None)

    # strip the '?' from sas token. the portal and command line are returns sas token in different
    # forms
    if n.sas_token:
        n.sas_token = n.sas_token.lstrip('?')

    # if account name is specified but no key, attempt to query
    if n.account_name and not n.account_key and not n.sas_token:
        n.account_key = _query_account_key(cmd.cli_ctx, n.account_name)
199943
def cli(env, identifier, no_vs, no_hardware):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)
    subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,
                                   name='subnet')
    subnet = mgr.get_subnet(subnet_id)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', subnet['id']])
    table.add_row(['identifier',
                   '%s/%s' % (subnet['networkIdentifier'],
                              str(subnet['cidr']))])
    table.add_row(['subnet type', subnet['subnetType']])
    table.add_row(['network space',
                   utils.lookup(subnet, 'networkVlan', 'networkSpace')])
    table.add_row(['gateway', subnet.get('gateway', formatting.blank())])
    table.add_row(['broadcast',
                   subnet.get('broadcastAddress', formatting.blank())])
    table.add_row(['datacenter', subnet['datacenter']['name']])
    table.add_row(['usable ips',
                   subnet.get('usableIpAddressCount', formatting.blank())])

    if not no_vs:
        if subnet['virtualGuests']:
            vs_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for vsi in subnet['virtualGuests']:
                vs_table.add_row([vsi['hostname'],
                                  vsi['domain'],
                                  vsi.get('primaryIpAddress'),
                                  vsi.get('primaryBackendIpAddress')])
            table.add_row(['vs', vs_table])
        else:
            table.add_row(['vs', 'none'])

    if not no_hardware:
        if subnet['hardware']:
            hw_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for hardware in subnet['hardware']:
                hw_table.add_row([hardware['hostname'],
                                  hardware['domain'],
                                  hardware.get('primaryIpAddress'),
                                  hardware.get('primaryBackendIpAddress')])
            table.add_row(['hardware', hw_table])
        else:
            table.add_row(['hardware', 'none'])

    env.fout(table)
457599
def sanitize_params(inputs)
      out = {}.with_indifferent_access
      _fields.each_pair do |field, config|
        next unless inputs.key?(field)

        out[field] = ::Subroutine::TypeCaster.cast(inputs[field], config)
      end

      out
    end