repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/modules/debian_service.py
disable
def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} remove'.format(name) else: cmd = 'update-rc.d {0} disable'.format(name) return not __salt__['cmd.retcode'](cmd)
python
def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} remove'.format(name) else: cmd = 'update-rc.d {0} disable'.format(name) return not __salt__['cmd.retcode'](cmd)
[ "def", "disable", "(", "name", ",", "*", "*", "kwargs", ")", ":", "osmajor", "=", "_osrel", "(", ")", "[", "0", "]", "if", "osmajor", "<", "'6'", ":", "cmd", "=", "'update-rc.d -f {0} remove'", ".", "format", "(", "name", ")", "else", ":", "cmd", "...
Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name>
[ "Disable", "the", "named", "service", "to", "start", "at", "boot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_service.py#L298-L313
train
saltstack/salt
salt/modules/keystone.py
_get_kwargs
def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs
python
def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs
[ "def", "_get_kwargs", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "if", "profile", ":", "prefix", "=", "profile", "+", "\":keystone.\"", "else", ":", "prefix", "=", "\"keystone.\"", "def", "get", "(", "key", ",", "default", "...
get connection args
[ "get", "connection", "args" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L94-L135
train
saltstack/salt
salt/modules/keystone.py
api_version
def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None
python
def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None
[ "def", "api_version", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kwargs", "=", "_get_kwargs", "(", "profile", "=", "profile", ",", "*", "*", "connection_args", ")", "auth_url", "=", "kwargs", ".", "get", "(", "'auth_url'", ...
Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version
[ "Returns", "the", "API", "version", "derived", "from", "endpoint", "s", "response", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L138-L154
train
saltstack/salt
salt/modules/keystone.py
auth
def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl
python
def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl
[ "def", "auth", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "__utils__", "[", "'versions.warn_until'", "]", "(", "'Neon'", ",", "(", "'The keystone module has been deprecated and will be removed in {version}. '", "'Please update to using the key...
Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth
[ "Set", "up", "keystone", "credentials", ".", "Only", "intended", "to", "be", "used", "within", "Keystone", "-", "enabled", "modules", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L157-L192
train
saltstack/salt
salt/modules/keystone.py
ec2_credentials_create
def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id}
python
def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id}
[ "def", "ec2_credentials_create", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "tenant_id", "=", "None", ",", "tenant", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "pro...
Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f
[ "Create", "EC2", "-", "compatible", "credentials", "for", "user", "per", "tenant" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L195-L229
train
saltstack/salt
salt/modules/keystone.py
ec2_credentials_delete
def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id)
python
def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id)
[ "def", "ec2_credentials_delete", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "access_key", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "conn...
Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442
[ "Delete", "EC2", "-", "compatible", "credentials" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L232-L255
train
saltstack/salt
salt/modules/keystone.py
ec2_credentials_get
def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret
python
def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret
[ "def", "ec2_credentials_get", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "access", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_...
Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f
[ "Return", "ec2_credentials", "for", "a", "user", "(", "keystone", "ec2", "-", "credentials", "-", "get", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L258-L288
train
saltstack/salt
salt/modules/keystone.py
ec2_credentials_list
def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret
python
def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret
[ "def", "ec2_credentials_list", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{"...
Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack
[ "Return", "a", "list", "of", "ec2_credentials", "for", "a", "specific", "user", "(", "keystone", "ec2", "-", "credentials", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L291-L318
train
saltstack/salt
salt/modules/keystone.py
endpoint_get
def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'}
python
def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'}
[ "def", "endpoint_get", "(", "service", ",", "region", "=", "None", ",", "profile", "=", "None", ",", "interface", "=", "None", ",", "*", "*", "connection_args", ")", ":", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "services", "=", "...
Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne]
[ "Return", "a", "specific", "endpoint", "(", "keystone", "endpoint", "-", "get", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L321-L349
train
saltstack/salt
salt/modules/keystone.py
endpoint_list
def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret
python
def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret
[ "def", "endpoint_list", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "for", "endpoint", "in", "kstone", ".", "endpoints", "....
Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list
[ "Return", "a", "list", "of", "available", "endpoints", "(", "keystone", "endpoints", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L352-L369
train
saltstack/salt
salt/modules/keystone.py
endpoint_create
def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args)
python
def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args)
[ "def", "endpoint_create", "(", "service", ",", "publicurl", "=", "None", ",", "internalurl", "=", "None", ",", "adminurl", "=", "None", ",", "region", "=", "None", ",", "profile", "=", "None", ",", "url", "=", "None", ",", "interface", "=", "None", ","...
Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne'
[ "Create", "an", "endpoint", "for", "an", "Openstack", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L372-L402
train
saltstack/salt
salt/modules/keystone.py
endpoint_delete
def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True
python
def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True
[ "def", "endpoint_delete", "(", "service", ",", "region", "=", "None", ",", "profile", "=", "None", ",", "interface", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", ...
Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne]
[ "Delete", "endpoints", "of", "an", "Openstack", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L405-L424
train
saltstack/salt
salt/modules/keystone.py
role_create
def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args)
python
def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args)
[ "def", "role_create", "(", "name", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "'Error'", "not", "in", "role_get", "(", "name", "=", "name"...
Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin
[ "Create", "a", "named", "role", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L427-L442
train
saltstack/salt
salt/modules/keystone.py
role_delete
def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret
python
def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret
[ "def", "role_delete", "(", "role_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "name", ":", "fo...
Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin
[ "Delete", "a", "role", "(", "keystone", "role", "-", "delete", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L445-L475
train
saltstack/salt
salt/modules/keystone.py
role_get
def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret
python
def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret
[ "def", "role_get", "(", "role_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "...
Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova
[ "Return", "a", "specific", "roles", "(", "keystone", "role", "-", "get", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L478-L503
train
saltstack/salt
salt/modules/keystone.py
role_list
def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret
python
def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret
[ "def", "role_list", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "for", "role", "in", "kstone", ".", "roles", ".", "list",...
Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list
[ "Return", "a", "list", "of", "available", "roles", "(", "keystone", "role", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L506-L522
train
saltstack/salt
salt/modules/keystone.py
service_create
def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args)
python
def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args)
[ "def", "service_create", "(", "name", ",", "service_type", ",", "description", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "service", ...
Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service'
[ "Add", "service", "to", "Keystone", "service", "catalog" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L525-L539
train
saltstack/salt
salt/modules/keystone.py
service_delete
def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id)
python
def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id)
[ "def", "service_delete", "(", "service_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "name", ":",...
Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova
[ "Delete", "a", "service", "from", "Keystone", "service", "catalog" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L542-L558
train
saltstack/salt
salt/modules/keystone.py
service_get
def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret
python
def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret
[ "def", "service_get", "(", "service_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}...
Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova
[ "Return", "a", "specific", "services", "(", "keystone", "service", "-", "get", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L561-L586
train
saltstack/salt
salt/modules/keystone.py
service_list
def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret
python
def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret
[ "def", "service_list", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "for", "service", "in", "kstone", ".", "services", ".", ...
Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list
[ "Return", "a", "list", "of", "available", "services", "(", "keystone", "services", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L589-L605
train
saltstack/salt
salt/modules/keystone.py
tenant_create
def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args)
python
def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args)
[ "def", "tenant_create", "(", "name", ",", "description", "=", "None", ",", "enabled", "=", "True", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "n...
Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False
[ "Create", "a", "keystone", "tenant" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L608-L622
train
saltstack/salt
salt/modules/keystone.py
tenant_delete
def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret
python
def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret
[ "def", "tenant_delete", "(", "tenant_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "name", ":", ...
Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo
[ "Delete", "a", "tenant", "(", "keystone", "tenant", "-", "delete", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L661-L686
train
saltstack/salt
salt/modules/keystone.py
project_delete
def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False
python
def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False
[ "def", "project_delete", "(", "project_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "_OS_IDENTITY_API_VERSION", ">"...
Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo
[ "Delete", "a", "project", "(", "keystone", "project", "-", "delete", ")", ".", "Overrides", "keystone", "tenant", "-", "delete", "form", "api", "V2", ".", "For", "keystone", "api", "V3", "only", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L689-L718
train
saltstack/salt
salt/modules/keystone.py
tenant_get
def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret
python
def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret
[ "def", "tenant_get", "(", "tenant_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}",...
Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova
[ "Return", "a", "specific", "tenants", "(", "keystone", "tenant", "-", "get", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L721-L748
train
saltstack/salt
salt/modules/keystone.py
project_get
def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False
python
def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False
[ "def", "project_get", "(", "project_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "_OS_IDENTITY_API_VERSION", ">", ...
Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova
[ "Return", "a", "specific", "projects", "(", "keystone", "project", "-", "get", ")", "Overrides", "keystone", "tenant", "-", "get", "form", "api", "V2", ".", "For", "keystone", "api", "V3", "only", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L751-L781
train
saltstack/salt
salt/modules/keystone.py
tenant_list
def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret
python
def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret
[ "def", "tenant_list", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "for", "tenant", "in", "getattr", "(", "kstone", ",", "...
Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list
[ "Return", "a", "list", "of", "available", "tenants", "(", "keystone", "tenants", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L784-L801
train
saltstack/salt
salt/modules/keystone.py
project_list
def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False
python
def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False
[ "def", "project_list", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "_OS_IDENTITY_API_VERSION", ">", "2", ":", "return", "tenant_list", "(", "profile", ",", "*...
Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list
[ "Return", "a", "list", "of", "available", "projects", "(", "keystone", "projects", "-", "list", ")", ".", "Overrides", "keystone", "tenants", "-", "list", "form", "api", "V2", ".", "For", "keystone", "api", "V3", "only", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L804-L826
train
saltstack/salt
salt/modules/keystone.py
tenant_update
def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool)))
python
def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool)))
[ "def", "tenant_update", "(", "tenant_id", "=", "None", ",", "name", "=", "None", ",", "description", "=", "None", ",", "enabled", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile...
Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com
[ "Update", "a", "tenant", "s", "information", "(", "keystone", "tenant", "-", "update", ")", "The", "following", "fields", "may", "be", "updated", ":", "name", "description", "enabled", ".", "Can", "only", "update", "name", "if", "targeting", "by", "ID" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L829-L864
train
saltstack/salt
salt/modules/keystone.py
project_update
def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False
python
def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False
[ "def", "project_update", "(", "project_id", "=", "None", ",", "name", "=", "None", ",", "description", "=", "None", ",", "enabled", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "auth", "(", "profile", ",", "*", ...
Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com
[ "Update", "a", "tenant", "s", "information", "(", "keystone", "project", "-", "update", ")", "The", "following", "fields", "may", "be", "updated", ":", "name", "description", "enabled", ".", "Can", "only", "update", "name", "if", "targeting", "by", "ID" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L867-L907
train
saltstack/salt
salt/modules/keystone.py
token_get
def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']}
python
def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']}
[ "def", "token_get", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "token", "=", "kstone", ".", "service_catalog", ".", "get_token", "(", ")", "return...
Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082
[ "Return", "the", "configured", "tokens", "(", "keystone", "token", "-", "get", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L910-L925
train
saltstack/salt
salt/modules/keystone.py
user_list
def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret
python
def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret
[ "def", "user_list", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "for", "user", "in", "kstone", ".", "users", ".", "list",...
Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list
[ "Return", "a", "list", "of", "available", "users", "(", "keystone", "user", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L928-L947
train
saltstack/salt
salt/modules/keystone.py
user_get
def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret
python
def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret
[ "def", "user_get", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "...
Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova
[ "Return", "a", "specific", "users", "(", "keystone", "user", "-", "get", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L950-L985
train
saltstack/salt
salt/modules/keystone.py
user_create
def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args)
python
def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args)
[ "def", "user_create", "(", "name", ",", "password", ",", "email", ",", "tenant_id", "=", "None", ",", "enabled", "=", "True", ",", "profile", "=", "None", ",", "project_id", "=", "None", ",", "description", "=", "None", ",", "*", "*", "connection_args", ...
Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True
[ "Create", "a", "user", "(", "keystone", "user", "-", "create", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L988-L1017
train
saltstack/salt
salt/modules/keystone.py
user_delete
def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret
python
def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret
[ "def", "user_delete", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "name", ":", "fo...
Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova
[ "Delete", "a", "user", "(", "keystone", "user", "-", "delete", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1020-L1045
train
saltstack/salt
salt/modules/keystone.py
user_update
def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret
python
def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret
[ "def", "user_update", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "email", "=", "None", ",", "enabled", "=", "None", ",", "tenant", "=", "None", ",", "profile", "=", "None", ",", "project", "=", "None", ",", "description", "=", "None"...
Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com
[ "Update", "a", "user", "s", "information", "(", "keystone", "user", "-", "update", ")", "The", "following", "fields", "may", "be", "updated", ":", "name", "email", "enabled", "tenant", ".", "Because", "the", "name", "is", "one", "of", "the", "fields", "a...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1048-L1109
train
saltstack/salt
salt/modules/keystone.py
user_verify_password
def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True
python
def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True
[ "def", "user_verify_password", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "password", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connecti...
Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar
[ "Verify", "a", "user", "s", "password" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1112-L1157
train
saltstack/salt
salt/modules/keystone.py
user_password_update
def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret
python
def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret
[ "def", "user_password_update", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "password", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connecti...
Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345
[ "Update", "a", "user", "s", "password", "(", "keystone", "user", "-", "password", "-", "update", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1160-L1189
train
saltstack/salt
salt/modules/keystone.py
user_role_add
def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant)
python
def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant)
[ "def", "user_role_add", "(", "user_id", "=", "None", ",", "user", "=", "None", ",", "tenant_id", "=", "None", ",", "tenant", "=", "None", ",", "role_id", "=", "None", ",", "role", "=", "None", ",", "profile", "=", "None", ",", "project_id", "=", "Non...
Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin
[ "Add", "role", "for", "user", "in", "tenant", "(", "keystone", "user", "-", "role", "-", "add", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1192-L1247
train
saltstack/salt
salt/modules/keystone.py
user_role_list
def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret
python
def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret
[ "def", "user_role_list", "(", "user_id", "=", "None", ",", "tenant_id", "=", "None", ",", "user_name", "=", "None", ",", "tenant_name", "=", "None", ",", "profile", "=", "None", ",", "project_id", "=", "None", ",", "project_name", "=", "None", ",", "*", ...
Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin
[ "Return", "a", "list", "of", "available", "user_roles", "(", "keystone", "user", "-", "roles", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1307-L1353
train
saltstack/salt
salt/modules/keystone.py
_item_list
def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret
python
def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret
[ "def", "_item_list", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "[", "]", "for", "item", "in", "kstone", ".", "items", ".", "list"...
Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list
[ "Template", "for", "writing", "list", "functions", "Return", "a", "list", "of", "available", "items", "(", "keystone", "items", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1356-L1375
train
saltstack/salt
salt/roster/sshconfig.py
_get_ssh_config_file
def _get_ssh_config_file(opts): ''' :return: Path to the .ssh/config file - usually <home>/.ssh/config ''' ssh_config_file = opts.get('ssh_config_file') if not os.path.isfile(ssh_config_file): raise IOError('Cannot find SSH config file') if not os.access(ssh_config_file, os.R_OK): raise IOError('Cannot access SSH config file: {}'.format(ssh_config_file)) return ssh_config_file
python
def _get_ssh_config_file(opts): ''' :return: Path to the .ssh/config file - usually <home>/.ssh/config ''' ssh_config_file = opts.get('ssh_config_file') if not os.path.isfile(ssh_config_file): raise IOError('Cannot find SSH config file') if not os.access(ssh_config_file, os.R_OK): raise IOError('Cannot access SSH config file: {}'.format(ssh_config_file)) return ssh_config_file
[ "def", "_get_ssh_config_file", "(", "opts", ")", ":", "ssh_config_file", "=", "opts", ".", "get", "(", "'ssh_config_file'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "ssh_config_file", ")", ":", "raise", "IOError", "(", "'Cannot find SSH config ...
:return: Path to the .ssh/config file - usually <home>/.ssh/config
[ ":", "return", ":", "Path", "to", "the", ".", "ssh", "/", "config", "file", "-", "usually", "<home", ">", "/", ".", "ssh", "/", "config" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L33-L42
train
saltstack/salt
salt/roster/sshconfig.py
parse_ssh_config
def parse_ssh_config(lines): ''' Parses lines from the SSH config to create roster targets. :param lines: Individual lines from the ssh config file :return: Dictionary of targets in similar style to the flat roster ''' # transform the list of individual lines into a list of sublists where each # sublist represents a single Host definition hosts = [] for line in lines: line = salt.utils.stringutils.to_unicode(line) if not line or line.startswith('#'): continue elif line.startswith('Host '): hosts.append([]) hosts[-1].append(line) # construct a dictionary of Host names to mapped roster properties targets = collections.OrderedDict() for host_data in hosts: target = collections.OrderedDict() hostnames = host_data[0].split()[1:] for line in host_data[1:]: for field in _ROSTER_FIELDS: match = re.match(field.pattern, line) if match: target[field.target_field] = match.group(1) for hostname in hostnames: targets[hostname] = target # apply matching for glob hosts wildcard_targets = [] non_wildcard_targets = [] for target in targets.keys(): if '*' in target or '?' in target: wildcard_targets.append(target) else: non_wildcard_targets.append(target) for pattern in wildcard_targets: for candidate in non_wildcard_targets: if fnmatch.fnmatch(candidate, pattern): targets[candidate].update(targets[pattern]) del targets[pattern] # finally, update the 'host' to refer to its declaration in the SSH config # so that its connection parameters can be utilized for target in targets: targets[target]['host'] = target return targets
python
def parse_ssh_config(lines): ''' Parses lines from the SSH config to create roster targets. :param lines: Individual lines from the ssh config file :return: Dictionary of targets in similar style to the flat roster ''' # transform the list of individual lines into a list of sublists where each # sublist represents a single Host definition hosts = [] for line in lines: line = salt.utils.stringutils.to_unicode(line) if not line or line.startswith('#'): continue elif line.startswith('Host '): hosts.append([]) hosts[-1].append(line) # construct a dictionary of Host names to mapped roster properties targets = collections.OrderedDict() for host_data in hosts: target = collections.OrderedDict() hostnames = host_data[0].split()[1:] for line in host_data[1:]: for field in _ROSTER_FIELDS: match = re.match(field.pattern, line) if match: target[field.target_field] = match.group(1) for hostname in hostnames: targets[hostname] = target # apply matching for glob hosts wildcard_targets = [] non_wildcard_targets = [] for target in targets.keys(): if '*' in target or '?' in target: wildcard_targets.append(target) else: non_wildcard_targets.append(target) for pattern in wildcard_targets: for candidate in non_wildcard_targets: if fnmatch.fnmatch(candidate, pattern): targets[candidate].update(targets[pattern]) del targets[pattern] # finally, update the 'host' to refer to its declaration in the SSH config # so that its connection parameters can be utilized for target in targets: targets[target]['host'] = target return targets
[ "def", "parse_ssh_config", "(", "lines", ")", ":", "# transform the list of individual lines into a list of sublists where each", "# sublist represents a single Host definition", "hosts", "=", "[", "]", "for", "line", "in", "lines", ":", "line", "=", "salt", ".", "utils", ...
Parses lines from the SSH config to create roster targets. :param lines: Individual lines from the ssh config file :return: Dictionary of targets in similar style to the flat roster
[ "Parses", "lines", "from", "the", "SSH", "config", "to", "create", "roster", "targets", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L45-L94
train
saltstack/salt
salt/roster/sshconfig.py
targets
def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets from the flat yaml file, checks opts for location but defaults to /etc/salt/roster ''' ssh_config_file = _get_ssh_config_file(__opts__) with salt.utils.files.fopen(ssh_config_file, 'r') as fp: all_minions = parse_ssh_config([line.rstrip() for line in fp]) rmatcher = RosterMatcher(all_minions, tgt, tgt_type) matched = rmatcher.targets() return matched
python
def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets from the flat yaml file, checks opts for location but defaults to /etc/salt/roster ''' ssh_config_file = _get_ssh_config_file(__opts__) with salt.utils.files.fopen(ssh_config_file, 'r') as fp: all_minions = parse_ssh_config([line.rstrip() for line in fp]) rmatcher = RosterMatcher(all_minions, tgt, tgt_type) matched = rmatcher.targets() return matched
[ "def", "targets", "(", "tgt", ",", "tgt_type", "=", "'glob'", ",", "*", "*", "kwargs", ")", ":", "ssh_config_file", "=", "_get_ssh_config_file", "(", "__opts__", ")", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "ssh_config_file", ",", ...
Return the targets from the flat yaml file, checks opts for location but defaults to /etc/salt/roster
[ "Return", "the", "targets", "from", "the", "flat", "yaml", "file", "checks", "opts", "for", "location", "but", "defaults", "to", "/", "etc", "/", "salt", "/", "roster" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L97-L107
train
saltstack/salt
salt/roster/sshconfig.py
RosterMatcher.ret_glob_minions
def ret_glob_minions(self): ''' Return minions that match via glob ''' minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions
python
def ret_glob_minions(self): ''' Return minions that match via glob ''' minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions
[ "def", "ret_glob_minions", "(", "self", ")", ":", "minions", "=", "{", "}", "for", "minion", "in", "self", ".", "raw", ":", "if", "fnmatch", ".", "fnmatch", "(", "minion", ",", "self", ".", "tgt", ")", ":", "data", "=", "self", ".", "get_data", "("...
Return minions that match via glob
[ "Return", "minions", "that", "match", "via", "glob" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L128-L138
train
saltstack/salt
salt/roster/sshconfig.py
RosterMatcher.get_data
def get_data(self, minion): ''' Return the configured ip ''' if isinstance(self.raw[minion], six.string_types): return {'host': self.raw[minion]} if isinstance(self.raw[minion], dict): return self.raw[minion] return False
python
def get_data(self, minion): ''' Return the configured ip ''' if isinstance(self.raw[minion], six.string_types): return {'host': self.raw[minion]} if isinstance(self.raw[minion], dict): return self.raw[minion] return False
[ "def", "get_data", "(", "self", ",", "minion", ")", ":", "if", "isinstance", "(", "self", ".", "raw", "[", "minion", "]", ",", "six", ".", "string_types", ")", ":", "return", "{", "'host'", ":", "self", ".", "raw", "[", "minion", "]", "}", "if", ...
Return the configured ip
[ "Return", "the", "configured", "ip" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L140-L148
train
saltstack/salt
salt/exceptions.py
SaltException.pack
def pack(self): ''' Pack this exception into a serializable dictionary that is safe for transport via msgpack ''' if six.PY3: return {'message': six.text_type(self), 'args': self.args} return dict(message=self.__unicode__(), args=self.args)
python
def pack(self): ''' Pack this exception into a serializable dictionary that is safe for transport via msgpack ''' if six.PY3: return {'message': six.text_type(self), 'args': self.args} return dict(message=self.__unicode__(), args=self.args)
[ "def", "pack", "(", "self", ")", ":", "if", "six", ".", "PY3", ":", "return", "{", "'message'", ":", "six", ".", "text_type", "(", "self", ")", ",", "'args'", ":", "self", ".", "args", "}", "return", "dict", "(", "message", "=", "self", ".", "__u...
Pack this exception into a serializable dictionary that is safe for transport via msgpack
[ "Pack", "this", "exception", "into", "a", "serializable", "dictionary", "that", "is", "safe", "for", "transport", "via", "msgpack" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/exceptions.py#L65-L72
train
saltstack/salt
salt/modules/namecheap_domains.py
reactivate
def reactivate(domain_name): ''' Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.reactivate') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainreactivateresult = response_xml.getElementsByTagName('DomainReactivateResult')[0] return salt.utils.namecheap.xml_to_dict(domainreactivateresult)
python
def reactivate(domain_name): ''' Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.reactivate') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainreactivateresult = response_xml.getElementsByTagName('DomainReactivateResult')[0] return salt.utils.namecheap.xml_to_dict(domainreactivateresult)
[ "def", "reactivate", "(", "domain_name", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "(", "'namecheap.domains.reactivate'", ")", "opts", "[", "'DomainName'", "]", "=", "domain_name", "response_xml", "=", "salt", ".", "utils"...
Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name
[ "Try", "to", "reactivate", "the", "expired", "domain", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L54-L80
train
saltstack/salt
salt/modules/namecheap_domains.py
renew
def renew(domain_name, years, promotion_code=None): ''' Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5 ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.renew') opts['DomainName'] = domain_name opts['Years'] = years if promotion_code is not None: opts['PromotionCode'] = promotion_code response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainrenewresult = response_xml.getElementsByTagName("DomainRenewResult")[0] return salt.utils.namecheap.xml_to_dict(domainrenewresult)
python
def renew(domain_name, years, promotion_code=None): ''' Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5 ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.renew') opts['DomainName'] = domain_name opts['Years'] = years if promotion_code is not None: opts['PromotionCode'] = promotion_code response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainrenewresult = response_xml.getElementsByTagName("DomainRenewResult")[0] return salt.utils.namecheap.xml_to_dict(domainrenewresult)
[ "def", "renew", "(", "domain_name", ",", "years", ",", "promotion_code", "=", "None", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "(", "'namecheap.domains.renew'", ")", "opts", "[", "'DomainName'", "]", "=", "domain_name",...
Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5
[ "Try", "to", "renew", "the", "specified", "expiring", "domain", "name", "for", "a", "specified", "number", "of", "years" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L83-L120
train
saltstack/salt
salt/modules/namecheap_domains.py
create
def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2 ''' idn_codes = ('afr', 'alb', 'ara', 'arg', 'arm', 'asm', 'ast', 'ave', 'awa', 'aze', 'bak', 'bal', 'ban', 'baq', 'bas', 'bel', 'ben', 'bho', 'bos', 'bul', 'bur', 'car', 'cat', 'che', 'chi', 'chv', 'cop', 'cos', 'cze', 'dan', 'div', 'doi', 'dut', 'eng', 'est', 'fao', 'fij', 'fin', 'fre', 'fry', 'geo', 'ger', 'gla', 'gle', 'gon', 'gre', 'guj', 'heb', 'hin', 'hun', 'inc', 'ind', 'inh', 'isl', 'ita', 'jav', 'jpn', 'kas', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mkd', 'mlt', 'mol', 'mon', 'mri', 'msa', 'nep', 'nor', 'ori', 'oss', 'pan', 'per', 'pol', 'por', 'pus', 'raj', 'rum', 'rus', 'san', 'scr', 'sin', 'slo', 'slv', 'smo', 'snd', 'som', 'spa', 'srd', 'srp', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tha', 'tib', 'tur', 'ukr', 'urd', 'uzb', 'vie', 'wel', 'yid') require_opts = ['AdminAddress1', 'AdminCity', 'AdminCountry', 'AdminEmailAddress', 'AdminFirstName', 'AdminLastName', 'AdminPhone', 'AdminPostalCode', 'AdminStateProvince', 'AuxBillingAddress1', 'AuxBillingCity', 'AuxBillingCountry', 'AuxBillingEmailAddress', 'AuxBillingFirstName', 'AuxBillingLastName', 'AuxBillingPhone', 'AuxBillingPostalCode', 'AuxBillingStateProvince', 'RegistrantAddress1', 'RegistrantCity', 'RegistrantCountry', 'RegistrantEmailAddress', 'RegistrantFirstName', 'RegistrantLastName', 'RegistrantPhone', 'RegistrantPostalCode', 'RegistrantStateProvince', 'TechAddress1', 'TechCity', 'TechCountry', 'TechEmailAddress', 'TechFirstName', 'TechLastName', 'TechPhone', 'TechPostalCode', 'TechStateProvince', 'Years'] opts = salt.utils.namecheap.get_opts('namecheap.domains.create') opts['DomainName'] = domain_name opts['Years'] = six.text_type(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: nextkey = prefix + suffix if nextkey not in kwargs: opts_dict[nextkey] = value for key, value in six.iteritems(kwargs): if key.startswith('Registrant'): add_to_opts(opts, kwargs, value, key[10:], ['Tech', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Tech'): add_to_opts(opts, kwargs, value, key[4:], ['Registrant', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Admin'): add_to_opts(opts, kwargs, value, key[5:], ['Registrant', 'Tech', 'AuxBilling', 'Billing']) if key.startswith('AuxBilling'): add_to_opts(opts, kwargs, value, key[10:], ['Registrant', 'Tech', 'Admin', 'Billing']) if key.startswith('Billing'): add_to_opts(opts, kwargs, value, key[7:], ['Registrant', 'Tech', 'Admin', 'AuxBilling']) if key == 'IdnCode' and key not in idn_codes: log.error('Invalid IdnCode') raise Exception('Invalid IdnCode') opts[key] = value for requiredkey in require_opts: if requiredkey not in opts: log.error('Missing required parameter \'%s\'', requiredkey) raise Exception('Missing required parameter \'{0}\''.format(requiredkey)) response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainresult = response_xml.getElementsByTagName("DomainCreateResult")[0] return salt.utils.namecheap.atts_to_dict(domainresult)
python
def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2 ''' idn_codes = ('afr', 'alb', 'ara', 'arg', 'arm', 'asm', 'ast', 'ave', 'awa', 'aze', 'bak', 'bal', 'ban', 'baq', 'bas', 'bel', 'ben', 'bho', 'bos', 'bul', 'bur', 'car', 'cat', 'che', 'chi', 'chv', 'cop', 'cos', 'cze', 'dan', 'div', 'doi', 'dut', 'eng', 'est', 'fao', 'fij', 'fin', 'fre', 'fry', 'geo', 'ger', 'gla', 'gle', 'gon', 'gre', 'guj', 'heb', 'hin', 'hun', 'inc', 'ind', 'inh', 'isl', 'ita', 'jav', 'jpn', 'kas', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mkd', 'mlt', 'mol', 'mon', 'mri', 'msa', 'nep', 'nor', 'ori', 'oss', 'pan', 'per', 'pol', 'por', 'pus', 'raj', 'rum', 'rus', 'san', 'scr', 'sin', 'slo', 'slv', 'smo', 'snd', 'som', 'spa', 'srd', 'srp', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tha', 'tib', 'tur', 'ukr', 'urd', 'uzb', 'vie', 'wel', 'yid') require_opts = ['AdminAddress1', 'AdminCity', 'AdminCountry', 'AdminEmailAddress', 'AdminFirstName', 'AdminLastName', 'AdminPhone', 'AdminPostalCode', 'AdminStateProvince', 'AuxBillingAddress1', 'AuxBillingCity', 'AuxBillingCountry', 'AuxBillingEmailAddress', 'AuxBillingFirstName', 'AuxBillingLastName', 'AuxBillingPhone', 'AuxBillingPostalCode', 'AuxBillingStateProvince', 'RegistrantAddress1', 'RegistrantCity', 'RegistrantCountry', 'RegistrantEmailAddress', 'RegistrantFirstName', 'RegistrantLastName', 'RegistrantPhone', 'RegistrantPostalCode', 'RegistrantStateProvince', 'TechAddress1', 'TechCity', 'TechCountry', 'TechEmailAddress', 'TechFirstName', 'TechLastName', 'TechPhone', 'TechPostalCode', 'TechStateProvince', 'Years'] opts = salt.utils.namecheap.get_opts('namecheap.domains.create') opts['DomainName'] = domain_name opts['Years'] = six.text_type(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: nextkey = prefix + suffix if nextkey not in kwargs: opts_dict[nextkey] = value for key, value in six.iteritems(kwargs): if key.startswith('Registrant'): add_to_opts(opts, kwargs, value, key[10:], ['Tech', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Tech'): add_to_opts(opts, kwargs, value, key[4:], ['Registrant', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Admin'): add_to_opts(opts, kwargs, value, key[5:], ['Registrant', 'Tech', 'AuxBilling', 'Billing']) if key.startswith('AuxBilling'): add_to_opts(opts, kwargs, value, key[10:], ['Registrant', 'Tech', 'Admin', 'Billing']) if key.startswith('Billing'): add_to_opts(opts, kwargs, value, key[7:], ['Registrant', 'Tech', 'Admin', 'AuxBilling']) if key == 'IdnCode' and key not in idn_codes: log.error('Invalid IdnCode') raise Exception('Invalid IdnCode') opts[key] = value for requiredkey in require_opts: if requiredkey not in opts: log.error('Missing required parameter \'%s\'', requiredkey) raise Exception('Missing required parameter \'{0}\''.format(requiredkey)) response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainresult = response_xml.getElementsByTagName("DomainCreateResult")[0] return salt.utils.namecheap.atts_to_dict(domainresult)
[ "def", "create", "(", "domain_name", ",", "years", ",", "*", "*", "kwargs", ")", ":", "idn_codes", "=", "(", "'afr'", ",", "'alb'", ",", "'ara'", ",", "'arg'", ",", "'arm'", ",", "'asm'", ",", "'ast'", ",", "'ave'", ",", "'awa'", ",", "'aze'", ",",...
Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2
[ "Try", "to", "register", "the", "specified", "domain", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L123-L209
train
saltstack/salt
salt/modules/namecheap_domains.py
check
def check(*domains_to_check): ''' Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.check') opts['DomainList'] = ','.join(domains_to_check) response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") domains_checked[result.getAttribute("Domain").lower()] = salt.utils.namecheap.string_to_value(available) return domains_checked
python
def check(*domains_to_check): ''' Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.check') opts['DomainList'] = ','.join(domains_to_check) response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") domains_checked[result.getAttribute("Domain").lower()] = salt.utils.namecheap.string_to_value(available) return domains_checked
[ "def", "check", "(", "*", "domains_to_check", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "(", "'namecheap.domains.check'", ")", "opts", "[", "'DomainList'", "]", "=", "','", ".", "join", "(", "domains_to_check", ")", "r...
Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check
[ "Checks", "the", "availability", "of", "domains" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L212-L241
train
saltstack/salt
salt/modules/namecheap_domains.py
get_info
def get_info(domain_name): ''' Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domaingetinforesult = response_xml.getElementsByTagName("DomainGetInfoResult")[0] return salt.utils.namecheap.xml_to_dict(domaingetinforesult)
python
def get_info(domain_name): ''' Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domaingetinforesult = response_xml.getElementsByTagName("DomainGetInfoResult")[0] return salt.utils.namecheap.xml_to_dict(domaingetinforesult)
[ "def", "get_info", "(", "domain_name", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "(", "'namecheap.domains.getinfo'", ")", "opts", "[", "'DomainName'", "]", "=", "domain_name", "response_xml", "=", "salt", ".", "utils", "...
Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name
[ "Returns", "information", "about", "the", "requested", "domain" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L244-L269
train
saltstack/salt
salt/modules/namecheap_domains.py
get_tld_list
def get_tld_list(): ''' Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list ''' response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist')) if response_xml is None: return [] tldresult = response_xml.getElementsByTagName("Tlds")[0] tlds = [] for e in tldresult.getElementsByTagName("Tld"): tld = salt.utils.namecheap.atts_to_dict(e) tld['data'] = e.firstChild.data categories = [] subcategories = e.getElementsByTagName("Categories")[0] for c in subcategories.getElementsByTagName("TldCategory"): categories.append(salt.utils.namecheap.atts_to_dict(c)) tld['categories'] = categories tlds.append(tld) return tlds
python
def get_tld_list(): ''' Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list ''' response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist')) if response_xml is None: return [] tldresult = response_xml.getElementsByTagName("Tlds")[0] tlds = [] for e in tldresult.getElementsByTagName("Tld"): tld = salt.utils.namecheap.atts_to_dict(e) tld['data'] = e.firstChild.data categories = [] subcategories = e.getElementsByTagName("Categories")[0] for c in subcategories.getElementsByTagName("TldCategory"): categories.append(salt.utils.namecheap.atts_to_dict(c)) tld['categories'] = categories tlds.append(tld) return tlds
[ "def", "get_tld_list", "(", ")", ":", "response_xml", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_request", "(", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "(", "'namecheap.domains.gettldlist'", ")", ")", "if", "response_xml", "is", ...
Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list
[ "Returns", "a", "list", "of", "TLDs", "as", "objects" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L272-L301
train
saltstack/salt
salt/modules/namecheap_domains.py
get_list
def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getList') if list_type is not None: if list_type not in ['ALL', 'EXPIRING', 'EXPIRED']: log.error('Invalid option for list_type') raise Exception('Invalid option for list_type') opts['ListType'] = list_type if search_term is not None: if len(search_term) > 70: log.warning('search_term trimmed to first 70 characters') search_term = search_term[0:70] opts['SearchTerm'] = search_term if page is not None: opts['Page'] = page if page_size is not None: if page_size > 100 or page_size < 10: log.error('Invalid option for page') raise Exception('Invalid option for page') opts['PageSize'] = page_size if sort_by is not None: if sort_by not in ['NAME', 'NAME_DESC', 'EXPIREDATE', 'EXPIREDATE_DESC', 'CREATEDATE', 'CREATEDATE_DESC']: log.error('Invalid option for sort_by') raise Exception('Invalid option for sort_by') opts['SortBy'] = sort_by response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domainresult = response_xml.getElementsByTagName("DomainGetListResult")[0] domains = [] for d in domainresult.getElementsByTagName("Domain"): domains.append(salt.utils.namecheap.atts_to_dict(d)) return domains
python
def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getList') if list_type is not None: if list_type not in ['ALL', 'EXPIRING', 'EXPIRED']: log.error('Invalid option for list_type') raise Exception('Invalid option for list_type') opts['ListType'] = list_type if search_term is not None: if len(search_term) > 70: log.warning('search_term trimmed to first 70 characters') search_term = search_term[0:70] opts['SearchTerm'] = search_term if page is not None: opts['Page'] = page if page_size is not None: if page_size > 100 or page_size < 10: log.error('Invalid option for page') raise Exception('Invalid option for page') opts['PageSize'] = page_size if sort_by is not None: if sort_by not in ['NAME', 'NAME_DESC', 'EXPIREDATE', 'EXPIREDATE_DESC', 'CREATEDATE', 'CREATEDATE_DESC']: log.error('Invalid option for sort_by') raise Exception('Invalid option for sort_by') opts['SortBy'] = sort_by response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domainresult = response_xml.getElementsByTagName("DomainGetListResult")[0] domains = [] for d in domainresult.getElementsByTagName("Domain"): domains.append(salt.utils.namecheap.atts_to_dict(d)) return domains
[ "def", "get_list", "(", "list_type", "=", "None", ",", "search_term", "=", "None", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "sort_by", "=", "None", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "...
Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list
[ "Returns", "a", "list", "of", "domains", "for", "the", "particular", "user", "as", "a", "list", "of", "objects", "offset", "by", "page", "length", "of", "page_size" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L304-L376
train
saltstack/salt
salt/pillar/reclass_adapter.py
ext_pillar
def ext_pillar(minion_id, pillar, **kwargs): ''' Obtain the Pillar data from **reclass** for the given ``minion_id``. ''' # If reclass is installed, __virtual__ put it onto the search path, so we # don't need to protect against ImportError: # pylint: disable=3rd-party-module-not-gated from reclass.adapters.salt import ext_pillar as reclass_ext_pillar from reclass.errors import ReclassException # pylint: enable=3rd-party-module-not-gated try: # the source path we used above isn't something reclass needs to care # about, so filter it: filter_out_source_path_option(kwargs) # if no inventory_base_uri was specified, initialize it to the first # file_roots of class 'base' (if that exists): set_inventory_base_uri_default(__opts__, kwargs) # I purposely do not pass any of __opts__ or __salt__ or __grains__ # to reclass, as I consider those to be Salt-internal and reclass # should not make any assumptions about it. return reclass_ext_pillar(minion_id, pillar, **kwargs) except TypeError as e: if 'unexpected keyword argument' in six.text_type(e): arg = six.text_type(e).split()[-1] raise SaltInvocationError('ext_pillar.reclass: unexpected option: ' + arg) else: raise except KeyError as e: if 'id' in six.text_type(e): raise SaltInvocationError('ext_pillar.reclass: __opts__ does not ' 'define minion ID') else: raise except ReclassException as e: raise SaltInvocationError('ext_pillar.reclass: {0}'.format(e))
python
def ext_pillar(minion_id, pillar, **kwargs): ''' Obtain the Pillar data from **reclass** for the given ``minion_id``. ''' # If reclass is installed, __virtual__ put it onto the search path, so we # don't need to protect against ImportError: # pylint: disable=3rd-party-module-not-gated from reclass.adapters.salt import ext_pillar as reclass_ext_pillar from reclass.errors import ReclassException # pylint: enable=3rd-party-module-not-gated try: # the source path we used above isn't something reclass needs to care # about, so filter it: filter_out_source_path_option(kwargs) # if no inventory_base_uri was specified, initialize it to the first # file_roots of class 'base' (if that exists): set_inventory_base_uri_default(__opts__, kwargs) # I purposely do not pass any of __opts__ or __salt__ or __grains__ # to reclass, as I consider those to be Salt-internal and reclass # should not make any assumptions about it. return reclass_ext_pillar(minion_id, pillar, **kwargs) except TypeError as e: if 'unexpected keyword argument' in six.text_type(e): arg = six.text_type(e).split()[-1] raise SaltInvocationError('ext_pillar.reclass: unexpected option: ' + arg) else: raise except KeyError as e: if 'id' in six.text_type(e): raise SaltInvocationError('ext_pillar.reclass: __opts__ does not ' 'define minion ID') else: raise except ReclassException as e: raise SaltInvocationError('ext_pillar.reclass: {0}'.format(e))
[ "def", "ext_pillar", "(", "minion_id", ",", "pillar", ",", "*", "*", "kwargs", ")", ":", "# If reclass is installed, __virtual__ put it onto the search path, so we", "# don't need to protect against ImportError:", "# pylint: disable=3rd-party-module-not-gated", "from", "reclass", "...
Obtain the Pillar data from **reclass** for the given ``minion_id``.
[ "Obtain", "the", "Pillar", "data", "from", "**", "reclass", "**", "for", "the", "given", "minion_id", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/reclass_adapter.py#L93-L135
train
saltstack/salt
salt/modules/zcbuildout.py
_set_status
def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m)
python
def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m)
[ "def", "_set_status", "(", "m", ",", "comment", "=", "INVALID_RESPONSE", ",", "status", "=", "False", ",", "out", "=", "None", ")", ":", "m", "[", "'out'", "]", "=", "out", "m", "[", "'status'", "]", "=", "status", "m", "[", "'logs'", "]", "=", "...
Assign status data to a dict.
[ "Assign", "status", "data", "to", "a", "dict", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L209-L248
train
saltstack/salt
salt/modules/zcbuildout.py
_invalid
def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out)
python
def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out)
[ "def", "_invalid", "(", "m", ",", "comment", "=", "INVALID_RESPONSE", ",", "out", "=", "None", ")", ":", "return", "_set_status", "(", "m", ",", "status", "=", "False", ",", "comment", "=", "comment", ",", "out", "=", "out", ")" ]
Return invalid status.
[ "Return", "invalid", "status", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L251-L255
train
saltstack/salt
salt/modules/zcbuildout.py
_valid
def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out)
python
def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out)
[ "def", "_valid", "(", "m", ",", "comment", "=", "VALID_RESPONSE", ",", "out", "=", "None", ")", ":", "return", "_set_status", "(", "m", ",", "status", "=", "True", ",", "comment", "=", "comment", ",", "out", "=", "out", ")" ]
Return valid status.
[ "Return", "valid", "status", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L258-L262
train
saltstack/salt
salt/modules/zcbuildout.py
_Popen
def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret
python
def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret
[ "def", "_Popen", "(", "command", ",", "output", "=", "False", ",", "directory", "=", "'.'", ",", "runas", "=", "None", ",", "env", "=", "(", ")", ",", "exitcode", "=", "0", ",", "use_vt", "=", "False", ",", "loglevel", "=", "None", ")", ":", "ret...
Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental]
[ "Run", "a", "command", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L265-L312
train
saltstack/salt
salt/modules/zcbuildout.py
_find_cfgs
def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs
python
def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs
[ "def", "_find_cfgs", "(", "path", ",", "cfgs", "=", "None", ")", ":", "ignored", "=", "[", "'var'", ",", "'parts'", "]", "dirs", "=", "[", "]", "if", "not", "cfgs", ":", "cfgs", "=", "[", "]", "for", "i", "in", "os", ".", "listdir", "(", "path"...
Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg
[ "Find", "all", "buildout", "configs", "in", "a", "subdirectory", ".", "only", "buildout", ".", "cfg", "and", "etc", "/", "buildout", ".", "cfg", "are", "valid", "in", "::" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L353-L388
train
saltstack/salt
salt/modules/zcbuildout.py
_get_bootstrap_content
def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent
python
def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent
[ "def", "_get_bootstrap_content", "(", "directory", "=", "'.'", ")", ":", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "directory", ")", ",", ...
Get the current bootstrap.py script content
[ "Get", "the", "current", "bootstrap", ".", "py", "script", "content" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L391-L404
train
saltstack/salt
salt/modules/zcbuildout.py
_get_buildout_ver
def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver
python
def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver
[ "def", "_get_buildout_ver", "(", "directory", "=", "'.'", ")", ":", "directory", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "buildoutver", "=", "2", "try", ":", "files", "=", "_find_cfgs", "(", "directory", ")", "for", "f", "in", "f...
Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in
[ "Check", "for", "buildout", "versions", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L407-L441
train
saltstack/salt
salt/modules/zcbuildout.py
_get_bootstrap_url
def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER])
python
def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER])
[ "def", "_get_bootstrap_url", "(", "directory", ")", ":", "v", "=", "_get_buildout_ver", "(", "directory", ")", "return", "_URL_VERSIONS", ".", "get", "(", "v", ",", "_URL_VERSIONS", "[", "DEFAULT_VER", "]", ")" ]
Get the most appropriate download URL for the bootstrap script. directory directory to execute in
[ "Get", "the", "most", "appropriate", "download", "URL", "for", "the", "bootstrap", "script", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L444-L453
train
saltstack/salt
salt/modules/zcbuildout.py
upgrade_bootstrap
def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment}
python
def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment}
[ "def", "upgrade_bootstrap", "(", "directory", "=", "'.'", ",", "onlyif", "=", "None", ",", "unless", "=", "None", ",", "runas", "=", "None", ",", "env", "=", "(", ")", ",", "offline", "=", "False", ",", "buildout_ver", "=", "None", ")", ":", "if", ...
Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout
[ "Upgrade", "current", "bootstrap", ".", "py", "with", "the", "last", "released", "one", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L468-L553
train
saltstack/salt
salt/modules/zcbuildout.py
bootstrap
def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output}
python
def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output}
[ "def", "bootstrap", "(", "directory", "=", "'.'", ",", "config", "=", "'buildout.cfg'", ",", "python", "=", "sys", ".", "executable", ",", "onlyif", "=", "None", ",", "unless", "=", "None", ",", "runas", "=", "None", ",", "env", "=", "(", ")", ",", ...
Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout
[ "Run", "the", "buildout", "bootstrap", "dance", "(", "python", "bootstrap", ".", "py", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L557-L764
train
saltstack/salt
salt/modules/zcbuildout.py
run_buildout
def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)}
python
def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)}
[ "def", "run_buildout", "(", "directory", "=", "'.'", ",", "config", "=", "'buildout.cfg'", ",", "parts", "=", "None", ",", "onlyif", "=", "None", ",", "unless", "=", "None", ",", "offline", "=", "False", ",", "newest", "=", "True", ",", "runas", "=", ...
Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout
[ "Run", "a", "buildout", "in", "a", "directory", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L768-L870
train
saltstack/salt
salt/modules/zcbuildout.py
buildout
def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret])
python
def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret])
[ "def", "buildout", "(", "directory", "=", "'.'", ",", "config", "=", "'buildout.cfg'", ",", "parts", "=", "None", ",", "runas", "=", "None", ",", "env", "=", "(", ")", ",", "buildout_ver", "=", "None", ",", "test_release", "=", "False", ",", "distribut...
Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout
[ "Run", "buildout", "in", "a", "directory", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L922-L1024
train
saltstack/salt
salt/pillar/sqlite3.py
ext_pillar
def ext_pillar(minion_id, pillar, *args, **kwargs): ''' Execute queries against SQLite3, merge and return as a dict ''' return SQLite3ExtPillar().fetch(minion_id, pillar, *args, **kwargs)
python
def ext_pillar(minion_id, pillar, *args, **kwargs): ''' Execute queries against SQLite3, merge and return as a dict ''' return SQLite3ExtPillar().fetch(minion_id, pillar, *args, **kwargs)
[ "def", "ext_pillar", "(", "minion_id", ",", "pillar", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "SQLite3ExtPillar", "(", ")", ".", "fetch", "(", "minion_id", ",", "pillar", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Execute queries against SQLite3, merge and return as a dict
[ "Execute", "queries", "against", "SQLite3", "merge", "and", "return", "as", "a", "dict" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/sqlite3.py#L110-L117
train
saltstack/salt
salt/pillar/http_json.py
ext_pillar
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 url, with_grains=False): ''' Read pillar data from HTTP response. :param str url: Url to request. :param bool with_grains: Whether to substitute strings in the url with their grain values. :return: A dictionary of the pillar data to add. :rtype: dict ''' url = url.replace('%s', _quote(minion_id)) grain_pattern = r'<(?P<grain_name>.*?)>' if with_grains: # Get the value of the grain and substitute each grain # name for the url-encoded version of its grain value. for match in re.finditer(grain_pattern, url): grain_name = match.group('grain_name') grain_value = __salt__['grains.get'](grain_name, None) if not grain_value: log.error("Unable to get minion '%s' grain: %s", minion_id, grain_name) return {} grain_value = _quote(six.text_type(grain_value)) url = re.sub('<{0}>'.format(grain_name), grain_value, url) log.debug('Getting url: %s', url) data = __salt__['http.query'](url=url, decode=True, decode_type='json') if 'dict' in data: return data['dict'] log.error("Error on minion '%s' http query: %s\nMore Info:\n", minion_id, url) for key in data: log.error('%s: %s', key, data[key]) return {}
python
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 url, with_grains=False): ''' Read pillar data from HTTP response. :param str url: Url to request. :param bool with_grains: Whether to substitute strings in the url with their grain values. :return: A dictionary of the pillar data to add. :rtype: dict ''' url = url.replace('%s', _quote(minion_id)) grain_pattern = r'<(?P<grain_name>.*?)>' if with_grains: # Get the value of the grain and substitute each grain # name for the url-encoded version of its grain value. for match in re.finditer(grain_pattern, url): grain_name = match.group('grain_name') grain_value = __salt__['grains.get'](grain_name, None) if not grain_value: log.error("Unable to get minion '%s' grain: %s", minion_id, grain_name) return {} grain_value = _quote(six.text_type(grain_value)) url = re.sub('<{0}>'.format(grain_name), grain_value, url) log.debug('Getting url: %s', url) data = __salt__['http.query'](url=url, decode=True, decode_type='json') if 'dict' in data: return data['dict'] log.error("Error on minion '%s' http query: %s\nMore Info:\n", minion_id, url) for key in data: log.error('%s: %s', key, data[key]) return {}
[ "def", "ext_pillar", "(", "minion_id", ",", "pillar", ",", "# pylint: disable=W0613", "url", ",", "with_grains", "=", "False", ")", ":", "url", "=", "url", ".", "replace", "(", "'%s'", ",", "_quote", "(", "minion_id", ")", ")", "grain_pattern", "=", "r'<(?...
Read pillar data from HTTP response. :param str url: Url to request. :param bool with_grains: Whether to substitute strings in the url with their grain values. :return: A dictionary of the pillar data to add. :rtype: dict
[ "Read", "pillar", "data", "from", "HTTP", "response", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/http_json.py#L66-L109
train
saltstack/salt
salt/modules/nxos.py
check_password
def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False
python
def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False
[ "def", "check_password", "(", "username", ",", "password", ",", "encrypted", "=", "False", ",", "*", "*", "kwargs", ")", ":", "hash_algorithms", "=", "{", "'1'", ":", "'md5'", ",", "'2a'", ":", "'blowfish'", ",", "'5'", ":", "'sha256'", ",", "'6'", ":"...
Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True
[ "Verify", "user", "password", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L143-L181
train
saltstack/salt
salt/modules/nxos.py
cmd
def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs)
python
def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs)
[ "def", "cmd", "(", "command", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "k", "in", "list", "(", "kwargs", ")", ":", "if", "k", ".", "startswith", "(", "'__pub_'", ")", ":", "kwargs", ".", "pop", "(", "k", ")", "local_command", ...
NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True
[ "NOTE", ":", "This", "function", "is", "preserved", "for", "backwards", "compatibilty", ".", "This", "allows", "commands", "to", "be", "executed", "using", "either", "of", "the", "following", "syntactic", "forms", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L195-L228
train
saltstack/salt
salt/modules/nxos.py
get_roles
def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles
python
def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles
[ "def", "get_roles", "(", "username", ",", "*", "*", "kwargs", ")", ":", "user", "=", "get_user", "(", "username", ")", "if", "not", "user", ":", "return", "[", "]", "command", "=", "'show user-account {0}'", ".", "format", "(", "username", ")", "info", ...
Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin
[ "Get", "roles", "assigned", "to", "a", "username", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L247-L268
train
saltstack/salt
salt/modules/nxos.py
get_user
def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info
python
def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info
[ "def", "get_user", "(", "username", ",", "*", "*", "kwargs", ")", ":", "command", "=", "'show run | include \"^username {0} password 5 \"'", ".", "format", "(", "username", ")", "info", "=", "''", "info", "=", "show", "(", "command", ",", "*", "*", "kwargs",...
Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin
[ "Get", "username", "line", "from", "switch", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L271-L284
train
saltstack/salt
salt/modules/nxos.py
grains
def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache']
python
def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache']
[ "def", "grains", "(", "*", "*", "kwargs", ")", ":", "if", "not", "DEVICE_DETAILS", "[", "'grains_cache'", "]", ":", "ret", "=", "salt", ".", "utils", ".", "nxos", ".", "system_info", "(", "show_ver", "(", "*", "*", "kwargs", ")", ")", "log", ".", "...
Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains
[ "Get", "grains", "for", "minion", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L287-L299
train
saltstack/salt
salt/modules/nxos.py
sendline
def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs)
python
def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs)
[ "def", "sendline", "(", "command", ",", "method", "=", "'cli_show_ascii'", ",", "*", "*", "kwargs", ")", ":", "smethods", "=", "[", "'cli_show_ascii'", ",", "'cli_show'", ",", "'cli_conf'", "]", "if", "method", "not", "in", "smethods", ":", "msg", "=", "...
Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"'
[ "Send", "arbitray", "commands", "to", "the", "NX", "-", "OS", "device", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L314-L345
train
saltstack/salt
salt/modules/nxos.py
show
def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list
python
def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list
[ "def", "show", "(", "commands", ",", "raw_text", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "raw_text", ",", "bool", ")", ":", "msg", "=", "\"\"\"\n INPUT ERROR: Second argument 'raw_text' must be either True or False\n ...
Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test
[ "Execute", "one", "or", "more", "show", "(", "non", "-", "configuration", ")", "commands", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L348-L388
train
saltstack/salt
salt/modules/nxos.py
show_ver
def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info
python
def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info
[ "def", "show_ver", "(", "*", "*", "kwargs", ")", ":", "command", "=", "'show version'", "info", "=", "''", "info", "=", "show", "(", "command", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "info", ",", "list", ")", ":", "info", "=", "info...
Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver
[ "Shortcut", "to", "run", "show", "version", "on", "the", "NX", "-", "OS", "device", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L391-L404
train
saltstack/salt
salt/modules/nxos.py
show_run
def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info
python
def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info
[ "def", "show_run", "(", "*", "*", "kwargs", ")", ":", "command", "=", "'show running-config'", "info", "=", "''", "info", "=", "show", "(", "command", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "info", ",", "list", ")", ":", "info", "=", ...
Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run
[ "Shortcut", "to", "run", "show", "running", "-", "config", "on", "the", "NX", "-", "OS", "device", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L407-L420
train
saltstack/salt
salt/modules/nxos.py
config
def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff
python
def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff
[ "def", "config", "(", "commands", "=", "None", ",", "config_file", "=", "None", ",", "template_engine", "=", "'jinja'", ",", "context", "=", "None", ",", "defaults", "=", "None", ",", "saltenv", "=", "'base'", ",", "*", "*", "kwargs", ")", ":", "initia...
Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}"
[ "Configures", "the", "Nexus", "switch", "with", "the", "specified", "commands", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L459-L556
train
saltstack/salt
salt/modules/nxos.py
delete_config
def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result
python
def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result
[ "def", "delete_config", "(", "lines", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "lines", ",", "list", ")", ":", "lines", "=", "[", "lines", "]", "for", "i", ",", "_", "in", "enumerate", "(", "lines", ")", ":", "lines", "[...
Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list.
[ "Delete", "one", "or", "more", "config", "lines", "to", "the", "switch", "running", "config", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L573-L604
train
saltstack/salt
salt/modules/nxos.py
set_password
def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs)
python
def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs)
[ "def", "set_password", "(", "username", ",", "password", ",", "encrypted", "=", "False", ",", "role", "=", "None", ",", "crypt_salt", "=", "None", ",", "algorithm", "=", "'sha256'", ",", "*", "*", "kwargs", ")", ":", "password_line", "=", "get_user", "("...
Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True
[ "Set", "users", "password", "on", "switch", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L667-L723
train
saltstack/salt
salt/modules/nxos.py
set_role
def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs)
python
def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs)
[ "def", "set_role", "(", "username", ",", "role", ",", "*", "*", "kwargs", ")", ":", "role_line", "=", "'username {0} role {1}'", ".", "format", "(", "username", ",", "role", ")", "return", "config", "(", "role_line", ",", "*", "*", "kwargs", ")" ]
Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin.
[ "Assign", "role", "to", "username", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L726-L746
train
saltstack/salt
salt/modules/nxos.py
unset_role
def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs)
python
def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs)
[ "def", "unset_role", "(", "username", ",", "role", ",", "*", "*", "kwargs", ")", ":", "role_line", "=", "'no username {0} role {1}'", ".", "format", "(", "username", ",", "role", ")", "return", "config", "(", "role_line", ",", "*", "*", "kwargs", ")" ]
Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin
[ "Remove", "role", "from", "username", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L749-L769
train
saltstack/salt
salt/modules/nxos.py
_configure_device
def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs)
python
def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs)
[ "def", "_configure_device", "(", "commands", ",", "*", "*", "kwargs", ")", ":", "if", "salt", ".", "utils", ".", "platform", ".", "is_proxy", "(", ")", ":", "return", "__proxy__", "[", "'nxos.proxy_config'", "]", "(", "commands", ",", "*", "*", "kwargs",...
Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH.
[ "Helper", "function", "to", "send", "configuration", "commands", "to", "the", "device", "over", "a", "proxy", "minion", "or", "native", "minion", "using", "NX", "-", "API", "or", "SSH", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L775-L783
train
saltstack/salt
salt/modules/nxos.py
_nxapi_config
def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret]
python
def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret]
[ "def", "_nxapi_config", "(", "commands", ",", "methods", "=", "'cli_conf'", ",", "bsb_arg", "=", "None", ",", "*", "*", "kwargs", ")", ":", "api_kwargs", "=", "__salt__", "[", "'config.get'", "]", "(", "'nxos'", ",", "{", "}", ")", "api_kwargs", ".", "...
Helper function to send configuration commands using NX-API.
[ "Helper", "function", "to", "send", "configuration", "commands", "using", "NX", "-", "API", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L786-L806
train
saltstack/salt
salt/modules/nxos.py
_nxapi_request
def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
python
def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
[ "def", "_nxapi_request", "(", "commands", ",", "method", "=", "'cli_conf'", ",", "*", "*", "kwargs", ")", ":", "if", "salt", ".", "utils", ".", "platform", ".", "is_proxy", "(", ")", ":", "return", "__proxy__", "[", "'nxos._nxapi_request'", "]", "(", "co...
Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``.
[ "Helper", "function", "to", "send", "exec", "and", "config", "requests", "over", "NX", "-", "API", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L809-L829
train
saltstack/salt
salt/utils/gzip_util.py
compress
def compress(data, compresslevel=9): ''' Returns the data compressed at gzip level compression. ''' buf = BytesIO() with open_fileobj(buf, 'wb', compresslevel) as ogz: if six.PY3 and not isinstance(data, bytes): data = data.encode(__salt_system_encoding__) ogz.write(data) compressed = buf.getvalue() return compressed
python
def compress(data, compresslevel=9): ''' Returns the data compressed at gzip level compression. ''' buf = BytesIO() with open_fileobj(buf, 'wb', compresslevel) as ogz: if six.PY3 and not isinstance(data, bytes): data = data.encode(__salt_system_encoding__) ogz.write(data) compressed = buf.getvalue() return compressed
[ "def", "compress", "(", "data", ",", "compresslevel", "=", "9", ")", ":", "buf", "=", "BytesIO", "(", ")", "with", "open_fileobj", "(", "buf", ",", "'wb'", ",", "compresslevel", ")", "as", "ogz", ":", "if", "six", ".", "PY3", "and", "not", "isinstanc...
Returns the data compressed at gzip level compression.
[ "Returns", "the", "data", "compressed", "at", "gzip", "level", "compression", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gzip_util.py#L54-L64
train
saltstack/salt
salt/utils/gzip_util.py
compress_file
def compress_file(fh_, compresslevel=9, chunk_size=1048576): ''' Generator that reads chunk_size bytes at a time from a file/filehandle and yields the compressed result of each read. .. note:: Each chunk is compressed separately. They cannot be stitched together to form a compressed file. This function is designed to break up a file into compressed chunks for transport and decompression/reassembly on a remote host. ''' try: bytes_read = int(chunk_size) if bytes_read != chunk_size: raise ValueError except ValueError: raise ValueError('chunk_size must be an integer') try: while bytes_read == chunk_size: buf = BytesIO() with open_fileobj(buf, 'wb', compresslevel) as ogz: try: bytes_read = ogz.write(fh_.read(chunk_size)) except AttributeError: # Open the file and re-attempt the read fh_ = salt.utils.files.fopen(fh_, 'rb') bytes_read = ogz.write(fh_.read(chunk_size)) yield buf.getvalue() finally: try: fh_.close() except AttributeError: pass
python
def compress_file(fh_, compresslevel=9, chunk_size=1048576): ''' Generator that reads chunk_size bytes at a time from a file/filehandle and yields the compressed result of each read. .. note:: Each chunk is compressed separately. They cannot be stitched together to form a compressed file. This function is designed to break up a file into compressed chunks for transport and decompression/reassembly on a remote host. ''' try: bytes_read = int(chunk_size) if bytes_read != chunk_size: raise ValueError except ValueError: raise ValueError('chunk_size must be an integer') try: while bytes_read == chunk_size: buf = BytesIO() with open_fileobj(buf, 'wb', compresslevel) as ogz: try: bytes_read = ogz.write(fh_.read(chunk_size)) except AttributeError: # Open the file and re-attempt the read fh_ = salt.utils.files.fopen(fh_, 'rb') bytes_read = ogz.write(fh_.read(chunk_size)) yield buf.getvalue() finally: try: fh_.close() except AttributeError: pass
[ "def", "compress_file", "(", "fh_", ",", "compresslevel", "=", "9", ",", "chunk_size", "=", "1048576", ")", ":", "try", ":", "bytes_read", "=", "int", "(", "chunk_size", ")", "if", "bytes_read", "!=", "chunk_size", ":", "raise", "ValueError", "except", "Va...
Generator that reads chunk_size bytes at a time from a file/filehandle and yields the compressed result of each read. .. note:: Each chunk is compressed separately. They cannot be stitched together to form a compressed file. This function is designed to break up a file into compressed chunks for transport and decompression/reassembly on a remote host.
[ "Generator", "that", "reads", "chunk_size", "bytes", "at", "a", "time", "from", "a", "file", "/", "filehandle", "and", "yields", "the", "compressed", "result", "of", "each", "read", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gzip_util.py#L74-L106
train
saltstack/salt
salt/modules/systemd_service.py
_root
def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path
python
def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path
[ "def", "_root", "(", "path", ",", "root", ")", ":", "if", "root", ":", "return", "os", ".", "path", ".", "join", "(", "root", ",", "os", ".", "path", ".", "relpath", "(", "path", ",", "os", ".", "path", ".", "sep", ")", ")", "else", ":", "ret...
Relocate an absolute path to a new root directory.
[ "Relocate", "an", "absolute", "path", "to", "a", "new", "root", "directory", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L73-L80
train
saltstack/salt
salt/modules/systemd_service.py
_canonical_unit_name
def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name
python
def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name
[ "def", "_canonical_unit_name", "(", "name", ")", ":", "if", "not", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", ":", "name", "=", "six", ".", "text_type", "(", "name", ")", "if", "any", "(", "name", ".", "endswith", "(", "suffix", ...
Build a canonical unit name treating unit names without one of the valid suffixes as a service.
[ "Build", "a", "canonical", "unit", "name", "treating", "unit", "names", "without", "one", "of", "the", "valid", "suffixes", "as", "a", "service", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L83-L92
train
saltstack/salt
salt/modules/systemd_service.py
_check_available
def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret
python
def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret
[ "def", "_check_available", "(", "name", ")", ":", "_status", "=", "_systemctl_status", "(", "name", ")", "sd_version", "=", "salt", ".", "utils", ".", "systemd", ".", "version", "(", "__context__", ")", "if", "sd_version", "is", "not", "None", "and", "sd_v...
Returns boolean telling whether or not the named service is available
[ "Returns", "boolean", "telling", "whether", "or", "not", "the", "named", "service", "is", "available" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L95-L125
train
saltstack/salt
salt/modules/systemd_service.py
_check_for_unit_changes
def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True
python
def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True
[ "def", "_check_for_unit_changes", "(", "name", ")", ":", "contextkey", "=", "'systemd._check_for_unit_changes.{0}'", ".", "format", "(", "name", ")", "if", "contextkey", "not", "in", "__context__", ":", "if", "_untracked_custom_unit_found", "(", "name", ")", "or", ...
Check for modified/updated unit files, and run a daemon-reload if any are found.
[ "Check", "for", "modified", "/", "updated", "unit", "files", "and", "run", "a", "daemon", "-", "reload", "if", "any", "are", "found", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L128-L138
train
saltstack/salt
salt/modules/systemd_service.py
_check_unmask
def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root)
python
def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root)
[ "def", "_check_unmask", "(", "name", ",", "unmask", ",", "unmask_runtime", ",", "root", "=", "None", ")", ":", "if", "unmask", ":", "unmask_", "(", "name", ",", "runtime", "=", "False", ",", "root", "=", "root", ")", "if", "unmask_runtime", ":", "unmas...
Common code for conditionally removing masks before making changes to a service's state.
[ "Common", "code", "for", "conditionally", "removing", "masks", "before", "making", "changes", "to", "a", "service", "s", "state", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L141-L149
train
saltstack/salt
salt/modules/systemd_service.py
_clear_context
def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue
python
def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue
[ "def", "_clear_context", "(", ")", ":", "# Using list() here because modifying a dictionary during iteration will", "# raise a RuntimeError.", "for", "key", "in", "list", "(", "__context__", ")", ":", "try", ":", "if", "key", ".", "startswith", "(", "'systemd._systemctl_s...
Remove context
[ "Remove", "context" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L152-L163
train
saltstack/salt
salt/modules/systemd_service.py
_default_runlevel
def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel
python
def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel
[ "def", "_default_runlevel", "(", ")", ":", "# Try to get the \"main\" default. If this fails, throw up our", "# hands and just guess \"2\", because things are horribly broken", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "'/etc/init/rc-sysinit.conf...
Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot
[ "Try", "to", "figure", "out", "the", "default", "runlevel", ".", "It", "is", "kept", "in", "/", "etc", "/", "init", "/", "rc", "-", "sysinit", ".", "conf", "but", "can", "be", "overridden", "with", "entries", "in", "/", "etc", "/", "inittab", "or", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L166-L208
train
saltstack/salt
salt/modules/systemd_service.py
_get_systemd_services
def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) return ret
python
def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) return ret
[ "def", "_get_systemd_services", "(", "root", ")", ":", "ret", "=", "set", "(", ")", "for", "path", "in", "SYSTEM_CONFIG_PATHS", "+", "(", "LOCAL_CONFIG_PATH", ",", ")", ":", "# Make sure user has access to the path, and if the path is a", "# link it's likely that another ...
Use os.listdir() to get all the unit files
[ "Use", "os", ".", "listdir", "()", "to", "get", "all", "the", "unit", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L211-L229
train
saltstack/salt
salt/modules/systemd_service.py
_get_sysv_services
def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret
python
def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret
[ "def", "_get_sysv_services", "(", "root", ",", "systemd_services", "=", "None", ")", ":", "initscript_path", "=", "_root", "(", "INITSCRIPT_PATH", ",", "root", ")", "try", ":", "sysv_services", "=", "os", ".", "listdir", "(", "initscript_path", ")", "except", ...
Use os.listdir() and os.access() to get all the initscripts
[ "Use", "os", ".", "listdir", "()", "and", "os", ".", "access", "()", "to", "get", "all", "the", "initscripts" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L232-L269
train
saltstack/salt
salt/modules/systemd_service.py
_get_service_exec
def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey]
python
def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey]
[ "def", "_get_service_exec", "(", ")", ":", "contextkey", "=", "'systemd._get_service_exec'", "if", "contextkey", "not", "in", "__context__", ":", "executables", "=", "(", "'update-rc.d'", ",", "'chkconfig'", ")", "for", "executable", "in", "executables", ":", "ser...
Returns the path to the sysv service manager (either update-rc.d or chkconfig)
[ "Returns", "the", "path", "to", "the", "sysv", "service", "manager", "(", "either", "update", "-", "rc", ".", "d", "or", "chkconfig", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L272-L291
train
saltstack/salt
salt/modules/systemd_service.py
_runlevel
def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret
python
def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret
[ "def", "_runlevel", "(", ")", ":", "contextkey", "=", "'systemd._runlevel'", "if", "contextkey", "in", "__context__", ":", "return", "__context__", "[", "contextkey", "]", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'runlevel'", ",", "python_shell", "...
Return the current runlevel
[ "Return", "the", "current", "runlevel" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L294-L308
train
saltstack/salt
salt/modules/systemd_service.py
_strip_scope
def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip()
python
def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip()
[ "def", "_strip_scope", "(", "msg", ")", ":", "ret", "=", "[", "]", "for", "line", "in", "msg", ".", "splitlines", "(", ")", ":", "if", "not", "line", ".", "endswith", "(", "'.scope'", ")", ":", "ret", ".", "append", "(", "line", ")", "return", "'...
Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text.
[ "Strip", "unnecessary", "message", "about", "running", "the", "command", "with", "--", "scope", "from", "stderr", "so", "that", "we", "can", "raise", "an", "exception", "with", "the", "remaining", "stderr", "text", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L311-L320
train
saltstack/salt
salt/modules/systemd_service.py
_systemctl_cmd
def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret
python
def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret
[ "def", "_systemctl_cmd", "(", "action", ",", "name", "=", "None", ",", "systemd_scope", "=", "False", ",", "no_block", "=", "False", ",", "root", "=", "None", ")", ":", "ret", "=", "[", "]", "if", "systemd_scope", "and", "salt", ".", "utils", ".", "s...
Build a systemctl command line. Treat unit names without one of the valid suffixes as a service.
[ "Build", "a", "systemctl", "command", "line", ".", "Treat", "unit", "names", "without", "one", "of", "the", "valid", "suffixes", "as", "a", "service", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L323-L346
train