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/boto_apigateway.py
describe_api_model
def describe_api_model(restApiId, modelName, flatten=True, region=None, key=None, keyid=None, profile=None): ''' Get a model by name for a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_model restApiId modelName [True] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) model = conn.get_model(restApiId=restApiId, modelName=modelName, flatten=flatten) return {'model': _convert_datetime_str(model)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_model(restApiId, modelName, flatten=True, region=None, key=None, keyid=None, profile=None): ''' Get a model by name for a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_model restApiId modelName [True] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) model = conn.get_model(restApiId=restApiId, modelName=modelName, flatten=flatten) return {'model': _convert_datetime_str(model)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_model", "(", "restApiId", ",", "modelName", ",", "flatten", "=", "True", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", ...
Get a model by name for a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_model restApiId modelName [True]
[ "Get", "a", "model", "by", "name", "for", "a", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1097-L1113
train
saltstack/salt
salt/modules/boto_apigateway.py
api_model_exists
def api_model_exists(restApiId, modelName, region=None, key=None, keyid=None, profile=None): ''' Check to see if the given modelName exists in the given restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.api_model_exists restApiId modelName ''' r = describe_api_model(restApiId, modelName, region=region, key=key, keyid=keyid, profile=profile) return {'exists': bool(r.get('model'))}
python
def api_model_exists(restApiId, modelName, region=None, key=None, keyid=None, profile=None): ''' Check to see if the given modelName exists in the given restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.api_model_exists restApiId modelName ''' r = describe_api_model(restApiId, modelName, region=region, key=key, keyid=keyid, profile=profile) return {'exists': bool(r.get('model'))}
[ "def", "api_model_exists", "(", "restApiId", ",", "modelName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "r", "=", "describe_api_model", "(", "restApiId", ",", "modelName", ",",...
Check to see if the given modelName exists in the given restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.api_model_exists restApiId modelName
[ "Check", "to", "see", "if", "the", "given", "modelName", "exists", "in", "the", "given", "restApiId" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1116-L1128
train
saltstack/salt
salt/modules/boto_apigateway.py
_api_model_patch_replace
def _api_model_patch_replace(conn, restApiId, modelName, path, value): ''' the replace patch operation on a Model resource ''' response = conn.update_model(restApiId=restApiId, modelName=modelName, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
python
def _api_model_patch_replace(conn, restApiId, modelName, path, value): ''' the replace patch operation on a Model resource ''' response = conn.update_model(restApiId=restApiId, modelName=modelName, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
[ "def", "_api_model_patch_replace", "(", "conn", ",", "restApiId", ",", "modelName", ",", "path", ",", "value", ")", ":", "response", "=", "conn", ".", "update_model", "(", "restApiId", "=", "restApiId", ",", "modelName", "=", "modelName", ",", "patchOperations...
the replace patch operation on a Model resource
[ "the", "replace", "patch", "operation", "on", "a", "Model", "resource" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1131-L1137
train
saltstack/salt
salt/modules/boto_apigateway.py
update_api_model_schema
def update_api_model_schema(restApiId, modelName, schema, region=None, key=None, keyid=None, profile=None): ''' update the schema (in python dictionary format) for the given model in the given restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.update_api_model_schema restApiId modelName schema ''' try: schema_json = salt.utils.json.dumps(schema) if isinstance(schema, dict) else schema conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = _api_model_patch_replace(conn, restApiId, modelName, '/schema', schema_json) return {'updated': True, 'model': _convert_datetime_str(response)} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
python
def update_api_model_schema(restApiId, modelName, schema, region=None, key=None, keyid=None, profile=None): ''' update the schema (in python dictionary format) for the given model in the given restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.update_api_model_schema restApiId modelName schema ''' try: schema_json = salt.utils.json.dumps(schema) if isinstance(schema, dict) else schema conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = _api_model_patch_replace(conn, restApiId, modelName, '/schema', schema_json) return {'updated': True, 'model': _convert_datetime_str(response)} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "update_api_model_schema", "(", "restApiId", ",", "modelName", ",", "schema", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "schema_json", "=", "salt", ".", "ut...
update the schema (in python dictionary format) for the given model in the given restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.update_api_model_schema restApiId modelName schema
[ "update", "the", "schema", "(", "in", "python", "dictionary", "format", ")", "for", "the", "given", "model", "in", "the", "given", "restApiId" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1140-L1157
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_api_model
def delete_api_model(restApiId, modelName, region=None, key=None, keyid=None, profile=None): ''' Delete a model identified by name in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_model restApiId modelName ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_model(restApiId=restApiId, modelName=modelName) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_api_model(restApiId, modelName, region=None, key=None, keyid=None, profile=None): ''' Delete a model identified by name in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_model restApiId modelName ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_model(restApiId=restApiId, modelName=modelName) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_api_model", "(", "restApiId", ",", "modelName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ...
Delete a model identified by name in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_model restApiId modelName
[ "Delete", "a", "model", "identified", "by", "name", "in", "a", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1160-L1176
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api_model
def create_api_model(restApiId, modelName, modelDescription, schema, contentType='application/json', region=None, key=None, keyid=None, profile=None): ''' Create a new model in a given API with a given schema, currently only contentType supported is 'application/json' CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_model restApiId modelName modelDescription '<schema>' 'content-type' ''' try: schema_json = salt.utils.json.dumps(schema) if isinstance(schema, dict) else schema conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) model = conn.create_model(restApiId=restApiId, name=modelName, description=modelDescription, schema=schema_json, contentType=contentType) return {'created': True, 'model': _convert_datetime_str(model)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api_model(restApiId, modelName, modelDescription, schema, contentType='application/json', region=None, key=None, keyid=None, profile=None): ''' Create a new model in a given API with a given schema, currently only contentType supported is 'application/json' CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_model restApiId modelName modelDescription '<schema>' 'content-type' ''' try: schema_json = salt.utils.json.dumps(schema) if isinstance(schema, dict) else schema conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) model = conn.create_model(restApiId=restApiId, name=modelName, description=modelDescription, schema=schema_json, contentType=contentType) return {'created': True, 'model': _convert_datetime_str(model)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api_model", "(", "restApiId", ",", "modelName", ",", "modelDescription", ",", "schema", ",", "contentType", "=", "'application/json'", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None",...
Create a new model in a given API with a given schema, currently only contentType supported is 'application/json' CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_model restApiId modelName modelDescription '<schema>' 'content-type'
[ "Create", "a", "new", "model", "in", "a", "given", "API", "with", "a", "given", "schema", "currently", "only", "contentType", "supported", "is", "application", "/", "json" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1179-L1199
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_integration
def describe_api_integration(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None): ''' Get an integration for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_integration restApiId resourcePath httpMethod ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) integration = conn.get_integration(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod) return {'integration': _convert_datetime_str(integration)} return {'error': 'no such resource'} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_integration(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None): ''' Get an integration for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_integration restApiId resourcePath httpMethod ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) integration = conn.get_integration(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod) return {'integration': _convert_datetime_str(integration)} return {'error': 'no such resource'} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_integration", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "resource", "=", "describe_api_r...
Get an integration for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_integration restApiId resourcePath httpMethod
[ "Get", "an", "integration", "for", "a", "given", "method", "in", "a", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1202-L1222
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_integration_response
def describe_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Get an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_integration_response restApiId resourcePath httpMethod statusCode ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.get_integration_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=statusCode) return {'response': _convert_datetime_str(response)} return {'error': 'no such resource'} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Get an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_integration_response restApiId resourcePath httpMethod statusCode ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.get_integration_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=statusCode) return {'response': _convert_datetime_str(response)} return {'error': 'no such resource'} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_integration_response", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "statusCode", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "res...
Get an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_integration_response restApiId resourcePath httpMethod statusCode
[ "Get", "an", "integration", "response", "for", "a", "given", "method", "in", "a", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1225-L1247
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_api_integration_response
def delete_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Deletes an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_integration_response restApiId resourcePath httpMethod statusCode ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_integration_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=statusCode) return {'deleted': True} return {'deleted': False, 'error': 'no such resource'} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Deletes an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_integration_response restApiId resourcePath httpMethod statusCode ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_integration_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=statusCode) return {'deleted': True} return {'deleted': False, 'error': 'no such resource'} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_api_integration_response", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "statusCode", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "resou...
Deletes an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_integration_response restApiId resourcePath httpMethod statusCode
[ "Deletes", "an", "integration", "response", "for", "a", "given", "method", "in", "a", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1273-L1295
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api_integration
def create_api_integration(restApiId, resourcePath, httpMethod, integrationType, integrationHttpMethod, uri, credentials, requestParameters=None, requestTemplates=None, region=None, key=None, keyid=None, profile=None): ''' Creates an integration for a given method in a given API. If integrationType is MOCK, uri and credential parameters will be ignored. uri is in the form of (substitute APIGATEWAY_REGION and LAMBDA_FUNC_ARN) "arn:aws:apigateway:APIGATEWAY_REGION:lambda:path/2015-03-31/functions/LAMBDA_FUNC_ARN/invocations" credentials is in the form of an iam role name or role arn. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_integration restApiId resourcePath httpMethod \\ integrationType integrationHttpMethod uri credentials ['{}' ['{}']] ''' try: credentials = _get_role_arn(credentials, region=region, key=key, keyid=keyid, profile=profile) resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: requestParameters = dict() if requestParameters is None else requestParameters requestTemplates = dict() if requestTemplates is None else requestTemplates conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if httpMethod.lower() == 'options': uri = "" credentials = "" integration = conn.put_integration(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, type=integrationType, integrationHttpMethod=integrationHttpMethod, uri=uri, credentials=credentials, requestParameters=requestParameters, requestTemplates=requestTemplates) return {'created': True, 'integration': integration} return {'created': False, 'error': 'no such resource'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api_integration(restApiId, resourcePath, httpMethod, integrationType, integrationHttpMethod, uri, credentials, requestParameters=None, requestTemplates=None, region=None, key=None, keyid=None, profile=None): ''' Creates an integration for a given method in a given API. If integrationType is MOCK, uri and credential parameters will be ignored. uri is in the form of (substitute APIGATEWAY_REGION and LAMBDA_FUNC_ARN) "arn:aws:apigateway:APIGATEWAY_REGION:lambda:path/2015-03-31/functions/LAMBDA_FUNC_ARN/invocations" credentials is in the form of an iam role name or role arn. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_integration restApiId resourcePath httpMethod \\ integrationType integrationHttpMethod uri credentials ['{}' ['{}']] ''' try: credentials = _get_role_arn(credentials, region=region, key=key, keyid=keyid, profile=profile) resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: requestParameters = dict() if requestParameters is None else requestParameters requestTemplates = dict() if requestTemplates is None else requestTemplates conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if httpMethod.lower() == 'options': uri = "" credentials = "" integration = conn.put_integration(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, type=integrationType, integrationHttpMethod=integrationHttpMethod, uri=uri, credentials=credentials, requestParameters=requestParameters, requestTemplates=requestTemplates) return {'created': True, 'integration': integration} return {'created': False, 'error': 'no such resource'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api_integration", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "integrationType", ",", "integrationHttpMethod", ",", "uri", ",", "credentials", ",", "requestParameters", "=", "None", ",", "requestTemplates", "=", "None", ",", "region...
Creates an integration for a given method in a given API. If integrationType is MOCK, uri and credential parameters will be ignored. uri is in the form of (substitute APIGATEWAY_REGION and LAMBDA_FUNC_ARN) "arn:aws:apigateway:APIGATEWAY_REGION:lambda:path/2015-03-31/functions/LAMBDA_FUNC_ARN/invocations" credentials is in the form of an iam role name or role arn. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_integration restApiId resourcePath httpMethod \\ integrationType integrationHttpMethod uri credentials ['{}' ['{}']]
[ "Creates", "an", "integration", "for", "a", "given", "method", "in", "a", "given", "API", ".", "If", "integrationType", "is", "MOCK", "uri", "and", "credential", "parameters", "will", "be", "ignored", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1312-L1352
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api_integration_response
def create_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, selectionPattern, responseParameters=None, responseTemplates=None, region=None, key=None, keyid=None, profile=None): ''' Creates an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_integration_response restApiId resourcePath httpMethod \\ statusCode selectionPattern ['{}' ['{}']] ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: responseParameters = dict() if responseParameters is None else responseParameters responseTemplates = dict() if responseTemplates is None else responseTemplates conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.put_integration_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=statusCode, selectionPattern=selectionPattern, responseParameters=responseParameters, responseTemplates=responseTemplates) return {'created': True, 'response': response} return {'created': False, 'error': 'no such resource'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, selectionPattern, responseParameters=None, responseTemplates=None, region=None, key=None, keyid=None, profile=None): ''' Creates an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_integration_response restApiId resourcePath httpMethod \\ statusCode selectionPattern ['{}' ['{}']] ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: responseParameters = dict() if responseParameters is None else responseParameters responseTemplates = dict() if responseTemplates is None else responseTemplates conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.put_integration_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=statusCode, selectionPattern=selectionPattern, responseParameters=responseParameters, responseTemplates=responseTemplates) return {'created': True, 'response': response} return {'created': False, 'error': 'no such resource'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api_integration_response", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "statusCode", ",", "selectionPattern", ",", "responseParameters", "=", "None", ",", "responseTemplates", "=", "None", ",", "region", "=", "None", ",", "key", "...
Creates an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_integration_response restApiId resourcePath httpMethod \\ statusCode selectionPattern ['{}' ['{}']]
[ "Creates", "an", "integration", "response", "for", "a", "given", "method", "in", "a", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1355-L1385
train
saltstack/salt
salt/modules/boto_apigateway.py
_filter_plans
def _filter_plans(attr, name, plans): ''' Helper to return list of usage plan items matching the given attribute value. ''' return [plan for plan in plans if plan[attr] == name]
python
def _filter_plans(attr, name, plans): ''' Helper to return list of usage plan items matching the given attribute value. ''' return [plan for plan in plans if plan[attr] == name]
[ "def", "_filter_plans", "(", "attr", ",", "name", ",", "plans", ")", ":", "return", "[", "plan", "for", "plan", "in", "plans", "if", "plan", "[", "attr", "]", "==", "name", "]" ]
Helper to return list of usage plan items matching the given attribute value.
[ "Helper", "to", "return", "list", "of", "usage", "plan", "items", "matching", "the", "given", "attribute", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1388-L1392
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_usage_plans
def describe_usage_plans(name=None, plan_id=None, region=None, key=None, keyid=None, profile=None): ''' Returns a list of existing usage plans, optionally filtered to match a given plan name .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_usage_plans salt myminion boto_apigateway.describe_usage_plans name='usage plan name' salt myminion boto_apigateway.describe_usage_plans plan_id='usage plan id' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) plans = _multi_call(conn.get_usage_plans, 'items') if name: plans = _filter_plans('name', name, plans) if plan_id: plans = _filter_plans('id', plan_id, plans) return {'plans': [_convert_datetime_str(plan) for plan in plans]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_usage_plans(name=None, plan_id=None, region=None, key=None, keyid=None, profile=None): ''' Returns a list of existing usage plans, optionally filtered to match a given plan name .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_usage_plans salt myminion boto_apigateway.describe_usage_plans name='usage plan name' salt myminion boto_apigateway.describe_usage_plans plan_id='usage plan id' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) plans = _multi_call(conn.get_usage_plans, 'items') if name: plans = _filter_plans('name', name, plans) if plan_id: plans = _filter_plans('id', plan_id, plans) return {'plans': [_convert_datetime_str(plan) for plan in plans]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_usage_plans", "(", "name", "=", "None", ",", "plan_id", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", ...
Returns a list of existing usage plans, optionally filtered to match a given plan name .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_usage_plans salt myminion boto_apigateway.describe_usage_plans name='usage plan name' salt myminion boto_apigateway.describe_usage_plans plan_id='usage plan id'
[ "Returns", "a", "list", "of", "existing", "usage", "plans", "optionally", "filtered", "to", "match", "a", "given", "plan", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1395-L1421
train
saltstack/salt
salt/modules/boto_apigateway.py
_validate_quota
def _validate_quota(quota): ''' Helper to verify that quota parameters are valid ''' if quota is not None: if not isinstance(quota, dict): raise TypeError('quota must be a dictionary, provided value: {0}'.format(quota)) periods = ['DAY', 'WEEK', 'MONTH'] if 'period' not in quota or quota['period'] not in periods: raise ValueError('quota must have a valid period specified, valid values are {0}'.format(','.join(periods))) if 'limit' not in quota: raise ValueError('quota limit must have a valid value')
python
def _validate_quota(quota): ''' Helper to verify that quota parameters are valid ''' if quota is not None: if not isinstance(quota, dict): raise TypeError('quota must be a dictionary, provided value: {0}'.format(quota)) periods = ['DAY', 'WEEK', 'MONTH'] if 'period' not in quota or quota['period'] not in periods: raise ValueError('quota must have a valid period specified, valid values are {0}'.format(','.join(periods))) if 'limit' not in quota: raise ValueError('quota limit must have a valid value')
[ "def", "_validate_quota", "(", "quota", ")", ":", "if", "quota", "is", "not", "None", ":", "if", "not", "isinstance", "(", "quota", ",", "dict", ")", ":", "raise", "TypeError", "(", "'quota must be a dictionary, provided value: {0}'", ".", "format", "(", "quot...
Helper to verify that quota parameters are valid
[ "Helper", "to", "verify", "that", "quota", "parameters", "are", "valid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1433-L1444
train
saltstack/salt
salt/modules/boto_apigateway.py
create_usage_plan
def create_usage_plan(name, description=None, throttle=None, quota=None, region=None, key=None, keyid=None, profile=None): ''' Creates a new usage plan with throttling and quotas optionally applied .. versionadded:: 2017.7.0 name Name of the usage plan throttle A dictionary consisting of the following keys: rateLimit requests per second at steady rate, float burstLimit maximum number of requests per second, integer quota A dictionary consisting of the following keys: limit number of allowed requests per specified quota period [required if quota parameter is present] offset number of requests to be subtracted from limit at the beginning of the period [optional] period quota period, must be one of DAY, WEEK, or MONTH. [required if quota parameter is present CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_usage_plan name='usage plan name' throttle='{"rateLimit": 10.0, "burstLimit": 10}' ''' try: _validate_throttle(throttle) _validate_quota(quota) values = dict(name=name) if description: values['description'] = description if throttle: values['throttle'] = throttle if quota: values['quota'] = quota conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.create_usage_plan(**values) return {'created': True, 'result': res} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)} except (TypeError, ValueError) as e: return {'error': six.text_type(e)}
python
def create_usage_plan(name, description=None, throttle=None, quota=None, region=None, key=None, keyid=None, profile=None): ''' Creates a new usage plan with throttling and quotas optionally applied .. versionadded:: 2017.7.0 name Name of the usage plan throttle A dictionary consisting of the following keys: rateLimit requests per second at steady rate, float burstLimit maximum number of requests per second, integer quota A dictionary consisting of the following keys: limit number of allowed requests per specified quota period [required if quota parameter is present] offset number of requests to be subtracted from limit at the beginning of the period [optional] period quota period, must be one of DAY, WEEK, or MONTH. [required if quota parameter is present CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_usage_plan name='usage plan name' throttle='{"rateLimit": 10.0, "burstLimit": 10}' ''' try: _validate_throttle(throttle) _validate_quota(quota) values = dict(name=name) if description: values['description'] = description if throttle: values['throttle'] = throttle if quota: values['quota'] = quota conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.create_usage_plan(**values) return {'created': True, 'result': res} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)} except (TypeError, ValueError) as e: return {'error': six.text_type(e)}
[ "def", "create_usage_plan", "(", "name", ",", "description", "=", "None", ",", "throttle", "=", "None", ",", "quota", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", ...
Creates a new usage plan with throttling and quotas optionally applied .. versionadded:: 2017.7.0 name Name of the usage plan throttle A dictionary consisting of the following keys: rateLimit requests per second at steady rate, float burstLimit maximum number of requests per second, integer quota A dictionary consisting of the following keys: limit number of allowed requests per specified quota period [required if quota parameter is present] offset number of requests to be subtracted from limit at the beginning of the period [optional] period quota period, must be one of DAY, WEEK, or MONTH. [required if quota parameter is present CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_usage_plan name='usage plan name' throttle='{"rateLimit": 10.0, "burstLimit": 10}'
[ "Creates", "a", "new", "usage", "plan", "with", "throttling", "and", "quotas", "optionally", "applied" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1447-L1502
train
saltstack/salt
salt/modules/boto_apigateway.py
update_usage_plan
def update_usage_plan(plan_id, throttle=None, quota=None, region=None, key=None, keyid=None, profile=None): ''' Updates an existing usage plan with throttling and quotas .. versionadded:: 2017.7.0 plan_id Id of the created usage plan throttle A dictionary consisting of the following keys: rateLimit requests per second at steady rate, float burstLimit maximum number of requests per second, integer quota A dictionary consisting of the following keys: limit number of allowed requests per specified quota period [required if quota parameter is present] offset number of requests to be subtracted from limit at the beginning of the period [optional] period quota period, must be one of DAY, WEEK, or MONTH. [required if quota parameter is present CLI Example: .. code-block:: bash salt myminion boto_apigateway.update_usage_plan plan_id='usage plan id' throttle='{"rateLimit": 10.0, "burstLimit": 10}' ''' try: _validate_throttle(throttle) _validate_quota(quota) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) patchOperations = [] if throttle is None: patchOperations.append({'op': 'remove', 'path': '/throttle'}) else: if 'rateLimit' in throttle: patchOperations.append({'op': 'replace', 'path': '/throttle/rateLimit', 'value': str(throttle['rateLimit'])}) # future lint: disable=blacklisted-function if 'burstLimit' in throttle: patchOperations.append({'op': 'replace', 'path': '/throttle/burstLimit', 'value': str(throttle['burstLimit'])}) # future lint: disable=blacklisted-function if quota is None: patchOperations.append({'op': 'remove', 'path': '/quota'}) else: patchOperations.append({'op': 'replace', 'path': '/quota/period', 'value': str(quota['period'])}) # future lint: disable=blacklisted-function patchOperations.append({'op': 'replace', 'path': '/quota/limit', 'value': str(quota['limit'])}) # future lint: disable=blacklisted-function if 'offset' in quota: patchOperations.append({'op': 'replace', 'path': '/quota/offset', 'value': str(quota['offset'])}) # future lint: disable=blacklisted-function if patchOperations: res = conn.update_usage_plan(usagePlanId=plan_id, patchOperations=patchOperations) return {'updated': True, 'result': res} return {'updated': False} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)} except (TypeError, ValueError) as e: return {'error': six.text_type(e)}
python
def update_usage_plan(plan_id, throttle=None, quota=None, region=None, key=None, keyid=None, profile=None): ''' Updates an existing usage plan with throttling and quotas .. versionadded:: 2017.7.0 plan_id Id of the created usage plan throttle A dictionary consisting of the following keys: rateLimit requests per second at steady rate, float burstLimit maximum number of requests per second, integer quota A dictionary consisting of the following keys: limit number of allowed requests per specified quota period [required if quota parameter is present] offset number of requests to be subtracted from limit at the beginning of the period [optional] period quota period, must be one of DAY, WEEK, or MONTH. [required if quota parameter is present CLI Example: .. code-block:: bash salt myminion boto_apigateway.update_usage_plan plan_id='usage plan id' throttle='{"rateLimit": 10.0, "burstLimit": 10}' ''' try: _validate_throttle(throttle) _validate_quota(quota) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) patchOperations = [] if throttle is None: patchOperations.append({'op': 'remove', 'path': '/throttle'}) else: if 'rateLimit' in throttle: patchOperations.append({'op': 'replace', 'path': '/throttle/rateLimit', 'value': str(throttle['rateLimit'])}) # future lint: disable=blacklisted-function if 'burstLimit' in throttle: patchOperations.append({'op': 'replace', 'path': '/throttle/burstLimit', 'value': str(throttle['burstLimit'])}) # future lint: disable=blacklisted-function if quota is None: patchOperations.append({'op': 'remove', 'path': '/quota'}) else: patchOperations.append({'op': 'replace', 'path': '/quota/period', 'value': str(quota['period'])}) # future lint: disable=blacklisted-function patchOperations.append({'op': 'replace', 'path': '/quota/limit', 'value': str(quota['limit'])}) # future lint: disable=blacklisted-function if 'offset' in quota: patchOperations.append({'op': 'replace', 'path': '/quota/offset', 'value': str(quota['offset'])}) # future lint: disable=blacklisted-function if patchOperations: res = conn.update_usage_plan(usagePlanId=plan_id, patchOperations=patchOperations) return {'updated': True, 'result': res} return {'updated': False} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)} except (TypeError, ValueError) as e: return {'error': six.text_type(e)}
[ "def", "update_usage_plan", "(", "plan_id", ",", "throttle", "=", "None", ",", "quota", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "_validate_throttle"...
Updates an existing usage plan with throttling and quotas .. versionadded:: 2017.7.0 plan_id Id of the created usage plan throttle A dictionary consisting of the following keys: rateLimit requests per second at steady rate, float burstLimit maximum number of requests per second, integer quota A dictionary consisting of the following keys: limit number of allowed requests per specified quota period [required if quota parameter is present] offset number of requests to be subtracted from limit at the beginning of the period [optional] period quota period, must be one of DAY, WEEK, or MONTH. [required if quota parameter is present CLI Example: .. code-block:: bash salt myminion boto_apigateway.update_usage_plan plan_id='usage plan id' throttle='{"rateLimit": 10.0, "burstLimit": 10}'
[ "Updates", "an", "existing", "usage", "plan", "with", "throttling", "and", "quotas" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1505-L1576
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_usage_plan
def delete_usage_plan(plan_id, region=None, key=None, keyid=None, profile=None): ''' Deletes usage plan identified by plan_id .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_usage_plan plan_id='usage plan id' ''' try: existing = describe_usage_plans(plan_id=plan_id, region=region, key=key, keyid=keyid, profile=profile) # don't attempt to delete the usage plan if it does not exist if 'error' in existing: return {'error': existing['error']} if 'plans' in existing and existing['plans']: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.delete_usage_plan(usagePlanId=plan_id) return {'deleted': True, 'usagePlanId': plan_id} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def delete_usage_plan(plan_id, region=None, key=None, keyid=None, profile=None): ''' Deletes usage plan identified by plan_id .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_usage_plan plan_id='usage plan id' ''' try: existing = describe_usage_plans(plan_id=plan_id, region=region, key=key, keyid=keyid, profile=profile) # don't attempt to delete the usage plan if it does not exist if 'error' in existing: return {'error': existing['error']} if 'plans' in existing and existing['plans']: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.delete_usage_plan(usagePlanId=plan_id) return {'deleted': True, 'usagePlanId': plan_id} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_usage_plan", "(", "plan_id", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "existing", "=", "describe_usage_plans", "(", "plan_id", "=", "plan_id", ",", ...
Deletes usage plan identified by plan_id .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_usage_plan plan_id='usage plan id'
[ "Deletes", "usage", "plan", "identified", "by", "plan_id" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1579-L1603
train
saltstack/salt
salt/modules/boto_apigateway.py
_update_usage_plan_apis
def _update_usage_plan_apis(plan_id, apis, op, region=None, key=None, keyid=None, profile=None): ''' Helper function that updates the usage plan identified by plan_id by adding or removing it to each of the stages, specified by apis parameter. apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage a string, which is the stage that the created API is deployed to. op 'add' or 'remove' ''' try: patchOperations = [] for api in apis: patchOperations.append({ 'op': op, 'path': '/apiStages', 'value': '{0}:{1}'.format(api['apiId'], api['stage']) }) res = None if patchOperations: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.update_usage_plan(usagePlanId=plan_id, patchOperations=patchOperations) return {'success': True, 'result': res} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)} except Exception as e: return {'error': e}
python
def _update_usage_plan_apis(plan_id, apis, op, region=None, key=None, keyid=None, profile=None): ''' Helper function that updates the usage plan identified by plan_id by adding or removing it to each of the stages, specified by apis parameter. apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage a string, which is the stage that the created API is deployed to. op 'add' or 'remove' ''' try: patchOperations = [] for api in apis: patchOperations.append({ 'op': op, 'path': '/apiStages', 'value': '{0}:{1}'.format(api['apiId'], api['stage']) }) res = None if patchOperations: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.update_usage_plan(usagePlanId=plan_id, patchOperations=patchOperations) return {'success': True, 'result': res} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)} except Exception as e: return {'error': e}
[ "def", "_update_usage_plan_apis", "(", "plan_id", ",", "apis", ",", "op", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "patchOperations", "=", "[", "]", "for", "api...
Helper function that updates the usage plan identified by plan_id by adding or removing it to each of the stages, specified by apis parameter. apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage a string, which is the stage that the created API is deployed to. op 'add' or 'remove'
[ "Helper", "function", "that", "updates", "the", "usage", "plan", "identified", "by", "plan_id", "by", "adding", "or", "removing", "it", "to", "each", "of", "the", "stages", "specified", "by", "apis", "parameter", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1606-L1639
train
saltstack/salt
salt/modules/boto_apigateway.py
attach_usage_plan_to_apis
def attach_usage_plan_to_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None): ''' Attaches given usage plan to each of the apis provided in a list of apiId and stage values .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage a string, which is the stage that the created API is deployed to. CLI Example: .. code-block:: bash salt myminion boto_apigateway.attach_usage_plan_to_apis plan_id='usage plan id' apis='[{"apiId": "some id 1", "stage": "some stage 1"}]' ''' return _update_usage_plan_apis(plan_id, apis, 'add', region=region, key=key, keyid=keyid, profile=profile)
python
def attach_usage_plan_to_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None): ''' Attaches given usage plan to each of the apis provided in a list of apiId and stage values .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage a string, which is the stage that the created API is deployed to. CLI Example: .. code-block:: bash salt myminion boto_apigateway.attach_usage_plan_to_apis plan_id='usage plan id' apis='[{"apiId": "some id 1", "stage": "some stage 1"}]' ''' return _update_usage_plan_apis(plan_id, apis, 'add', region=region, key=key, keyid=keyid, profile=profile)
[ "def", "attach_usage_plan_to_apis", "(", "plan_id", ",", "apis", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "_update_usage_plan_apis", "(", "plan_id", ",", "apis", ",", ...
Attaches given usage plan to each of the apis provided in a list of apiId and stage values .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage a string, which is the stage that the created API is deployed to. CLI Example: .. code-block:: bash salt myminion boto_apigateway.attach_usage_plan_to_apis plan_id='usage plan id' apis='[{"apiId": "some id 1", "stage": "some stage 1"}]'
[ "Attaches", "given", "usage", "plan", "to", "each", "of", "the", "apis", "provided", "in", "a", "list", "of", "apiId", "and", "stage", "values" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1642-L1664
train
saltstack/salt
salt/modules/boto_apigateway.py
detach_usage_plan_from_apis
def detach_usage_plan_from_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None): ''' Detaches given usage plan from each of the apis provided in a list of apiId and stage value .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage a string, which is the stage that the created API is deployed to. CLI Example: .. code-block:: bash salt myminion boto_apigateway.detach_usage_plan_to_apis plan_id='usage plan id' apis='[{"apiId": "some id 1", "stage": "some stage 1"}]' ''' return _update_usage_plan_apis(plan_id, apis, 'remove', region=region, key=key, keyid=keyid, profile=profile)
python
def detach_usage_plan_from_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None): ''' Detaches given usage plan from each of the apis provided in a list of apiId and stage value .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage a string, which is the stage that the created API is deployed to. CLI Example: .. code-block:: bash salt myminion boto_apigateway.detach_usage_plan_to_apis plan_id='usage plan id' apis='[{"apiId": "some id 1", "stage": "some stage 1"}]' ''' return _update_usage_plan_apis(plan_id, apis, 'remove', region=region, key=key, keyid=keyid, profile=profile)
[ "def", "detach_usage_plan_from_apis", "(", "plan_id", ",", "apis", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "_update_usage_plan_apis", "(", "plan_id", ",", "apis", ",",...
Detaches given usage plan from each of the apis provided in a list of apiId and stage value .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage a string, which is the stage that the created API is deployed to. CLI Example: .. code-block:: bash salt myminion boto_apigateway.detach_usage_plan_to_apis plan_id='usage plan id' apis='[{"apiId": "some id 1", "stage": "some stage 1"}]'
[ "Detaches", "given", "usage", "plan", "from", "each", "of", "the", "apis", "provided", "in", "a", "list", "of", "apiId", "and", "stage", "value" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1667-L1689
train
saltstack/salt
salt/modules/zpool.py
_clean_vdev_config
def _clean_vdev_config(config): ''' Return a simple vdev tree from zpool.status' config section ''' cln_config = OrderedDict() for label, sub_config in config.items(): if label not in ['state', 'read', 'write', 'cksum']: sub_config = _clean_vdev_config(sub_config) if sub_config and isinstance(cln_config, list): cln_config.append(OrderedDict([(label, sub_config)])) elif sub_config and isinstance(cln_config, OrderedDict): cln_config[label] = sub_config elif isinstance(cln_config, list): cln_config.append(label) elif isinstance(cln_config, OrderedDict): new_config = [] for old_label, old_config in cln_config.items(): new_config.append(OrderedDict([(old_label, old_config)])) new_config.append(label) cln_config = new_config else: cln_config = [label] return cln_config
python
def _clean_vdev_config(config): ''' Return a simple vdev tree from zpool.status' config section ''' cln_config = OrderedDict() for label, sub_config in config.items(): if label not in ['state', 'read', 'write', 'cksum']: sub_config = _clean_vdev_config(sub_config) if sub_config and isinstance(cln_config, list): cln_config.append(OrderedDict([(label, sub_config)])) elif sub_config and isinstance(cln_config, OrderedDict): cln_config[label] = sub_config elif isinstance(cln_config, list): cln_config.append(label) elif isinstance(cln_config, OrderedDict): new_config = [] for old_label, old_config in cln_config.items(): new_config.append(OrderedDict([(old_label, old_config)])) new_config.append(label) cln_config = new_config else: cln_config = [label] return cln_config
[ "def", "_clean_vdev_config", "(", "config", ")", ":", "cln_config", "=", "OrderedDict", "(", ")", "for", "label", ",", "sub_config", "in", "config", ".", "items", "(", ")", ":", "if", "label", "not", "in", "[", "'state'", ",", "'read'", ",", "'write'", ...
Return a simple vdev tree from zpool.status' config section
[ "Return", "a", "simple", "vdev", "tree", "from", "zpool", ".", "status", "config", "section" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L48-L72
train
saltstack/salt
salt/modules/zpool.py
status
def status(zpool=None): ''' Return the status of the named zpool zpool : string optional name of storage pool .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.status myzpool ''' ret = OrderedDict() ## collect status output res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']('status', target=zpool), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) # NOTE: command output for reference # ===================================================================== # pool: data # state: ONLINE # scan: scrub repaired 0 in 2h27m with 0 errors on Mon Jan 8 03:27:25 2018 # config: # # NAME STATE READ WRITE CKSUM # data ONLINE 0 0 0 # mirror-0 ONLINE 0 0 0 # c0tXXXXCXXXXXXXXXXXd0 ONLINE 0 0 0 # c0tXXXXCXXXXXXXXXXXd0 ONLINE 0 0 0 # c0tXXXXCXXXXXXXXXXXd0 ONLINE 0 0 0 # # errors: No known data errors # ===================================================================== ## parse status output # NOTE: output is 'key: value' except for the 'config' key. # mulitple pools will repeat the output, so if switch pools if # we see 'pool:' current_pool = None current_prop = None for zpd in res['stdout'].splitlines(): if zpd.strip() == '': continue if ':' in zpd: # NOTE: line is 'key: value' format, we just update a dict prop = zpd.split(':')[0].strip() value = ":".join(zpd.split(':')[1:]).strip() if prop == 'pool' and current_pool != value: current_pool = value ret[current_pool] = OrderedDict() if prop != 'pool': ret[current_pool][prop] = value current_prop = prop else: # NOTE: we append the line output to the last property # this should only happens once we hit the config # section ret[current_pool][current_prop] = "{0}\n{1}".format( ret[current_pool][current_prop], zpd ) ## parse config property for each pool # NOTE: the config property has some structured data # sadly this data is in a different format than # the rest and it needs further processing for pool in ret: if 'config' not in ret[pool]: continue header = None root_vdev = None vdev = None dev = None rdev = None config = ret[pool]['config'] config_data = OrderedDict() for line in config.splitlines(): # NOTE: the first line is the header # we grab all the none whitespace values if not header: header = line.strip().lower() header = [x for x in header.split(' ') if x not in ['']] continue # NOTE: data is indented by 1 tab, then multiples of 2 spaces # to differential root vdev, vdev, and dev # # we just strip the intial tab (can't use .strip() here) if line[0] == "\t": line = line[1:] # NOTE: transform data into dict stat_data = OrderedDict(list(zip( header, [x for x in line.strip().split(' ') if x not in ['']], ))) # NOTE: decode the zfs values properly stat_data = __utils__['zfs.from_auto_dict'](stat_data) # NOTE: store stat_data in the proper location if line.startswith(' ' * 6): rdev = stat_data['name'] config_data[root_vdev][vdev][dev][rdev] = stat_data elif line.startswith(' ' * 4): rdev = None dev = stat_data['name'] config_data[root_vdev][vdev][dev] = stat_data elif line.startswith(' ' * 2): rdev = dev = None vdev = stat_data['name'] config_data[root_vdev][vdev] = stat_data else: rdev = dev = vdev = None root_vdev = stat_data['name'] config_data[root_vdev] = stat_data # NOTE: name already used as identifier, drop duplicate data del stat_data['name'] ret[pool]['config'] = config_data return ret
python
def status(zpool=None): ''' Return the status of the named zpool zpool : string optional name of storage pool .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.status myzpool ''' ret = OrderedDict() ## collect status output res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']('status', target=zpool), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) # NOTE: command output for reference # ===================================================================== # pool: data # state: ONLINE # scan: scrub repaired 0 in 2h27m with 0 errors on Mon Jan 8 03:27:25 2018 # config: # # NAME STATE READ WRITE CKSUM # data ONLINE 0 0 0 # mirror-0 ONLINE 0 0 0 # c0tXXXXCXXXXXXXXXXXd0 ONLINE 0 0 0 # c0tXXXXCXXXXXXXXXXXd0 ONLINE 0 0 0 # c0tXXXXCXXXXXXXXXXXd0 ONLINE 0 0 0 # # errors: No known data errors # ===================================================================== ## parse status output # NOTE: output is 'key: value' except for the 'config' key. # mulitple pools will repeat the output, so if switch pools if # we see 'pool:' current_pool = None current_prop = None for zpd in res['stdout'].splitlines(): if zpd.strip() == '': continue if ':' in zpd: # NOTE: line is 'key: value' format, we just update a dict prop = zpd.split(':')[0].strip() value = ":".join(zpd.split(':')[1:]).strip() if prop == 'pool' and current_pool != value: current_pool = value ret[current_pool] = OrderedDict() if prop != 'pool': ret[current_pool][prop] = value current_prop = prop else: # NOTE: we append the line output to the last property # this should only happens once we hit the config # section ret[current_pool][current_prop] = "{0}\n{1}".format( ret[current_pool][current_prop], zpd ) ## parse config property for each pool # NOTE: the config property has some structured data # sadly this data is in a different format than # the rest and it needs further processing for pool in ret: if 'config' not in ret[pool]: continue header = None root_vdev = None vdev = None dev = None rdev = None config = ret[pool]['config'] config_data = OrderedDict() for line in config.splitlines(): # NOTE: the first line is the header # we grab all the none whitespace values if not header: header = line.strip().lower() header = [x for x in header.split(' ') if x not in ['']] continue # NOTE: data is indented by 1 tab, then multiples of 2 spaces # to differential root vdev, vdev, and dev # # we just strip the intial tab (can't use .strip() here) if line[0] == "\t": line = line[1:] # NOTE: transform data into dict stat_data = OrderedDict(list(zip( header, [x for x in line.strip().split(' ') if x not in ['']], ))) # NOTE: decode the zfs values properly stat_data = __utils__['zfs.from_auto_dict'](stat_data) # NOTE: store stat_data in the proper location if line.startswith(' ' * 6): rdev = stat_data['name'] config_data[root_vdev][vdev][dev][rdev] = stat_data elif line.startswith(' ' * 4): rdev = None dev = stat_data['name'] config_data[root_vdev][vdev][dev] = stat_data elif line.startswith(' ' * 2): rdev = dev = None vdev = stat_data['name'] config_data[root_vdev][vdev] = stat_data else: rdev = dev = vdev = None root_vdev = stat_data['name'] config_data[root_vdev] = stat_data # NOTE: name already used as identifier, drop duplicate data del stat_data['name'] ret[pool]['config'] = config_data return ret
[ "def", "status", "(", "zpool", "=", "None", ")", ":", "ret", "=", "OrderedDict", "(", ")", "## collect status output", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zpool_command'", "]", "(", "'status'", ",", "target", "=", ...
Return the status of the named zpool zpool : string optional name of storage pool .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.status myzpool
[ "Return", "the", "status", "of", "the", "named", "zpool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L100-L233
train
saltstack/salt
salt/modules/zpool.py
iostat
def iostat(zpool=None, sample_time=5, parsable=True): ''' Display I/O statistics for the given pools zpool : string optional name of storage pool sample_time : int seconds to capture data before output default a sample of 5 seconds is used parsable : boolean display data in pythonc values (True, False, Bytes,...) .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 Added ```parsable``` parameter that defaults to True CLI Example: .. code-block:: bash salt '*' zpool.iostat myzpool ''' ret = OrderedDict() ## get iostat output res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='iostat', flags=['-v'], target=[zpool, sample_time, 2] ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) # NOTE: command output for reference # ===================================================================== # capacity operations bandwidth # pool alloc free read write read write # ------------------------- ----- ----- ----- ----- ----- ----- # mypool 648G 1.18T 10 6 1.30M 817K # mirror 648G 1.18T 10 6 1.30M 817K # c0tXXXXCXXXXXXXXXXXd0 - - 9 5 1.29M 817K # c0tXXXXCXXXXXXXXXXXd0 - - 9 5 1.29M 817K # c0tXXXXCXXXXXXXXXXXd0 - - 9 5 1.29M 817K # ------------------------- ----- ----- ----- ----- ----- ----- # ===================================================================== ## parse iostat output # NOTE: hardcode the header # the double header line is hard to parse, we opt to # hardcode the header fields header = [ 'name', 'capacity-alloc', 'capacity-free', 'operations-read', 'operations-write', 'bandwith-read', 'bandwith-write', ] root_vdev = None vdev = None dev = None current_data = OrderedDict() for line in res['stdout'].splitlines(): # NOTE: skip header if line.strip() == '' or \ line.strip().split()[-1] in ['write', 'bandwidth']: continue # NOTE: reset pool on line separator if line.startswith('-') and line.endswith('-'): ret.update(current_data) current_data = OrderedDict() continue # NOTE: transform data into dict io_data = OrderedDict(list(zip( header, [x for x in line.strip().split(' ') if x not in ['']], ))) # NOTE: normalize values if parsable: # NOTE: raw numbers and pythonic types io_data = __utils__['zfs.from_auto_dict'](io_data) else: # NOTE: human readable zfs types io_data = __utils__['zfs.to_auto_dict'](io_data) # NOTE: store io_data in the proper location if line.startswith(' ' * 4): dev = io_data['name'] current_data[root_vdev][vdev][dev] = io_data elif line.startswith(' ' * 2): dev = None vdev = io_data['name'] current_data[root_vdev][vdev] = io_data else: dev = vdev = None root_vdev = io_data['name'] current_data[root_vdev] = io_data # NOTE: name already used as identifier, drop duplicate data del io_data['name'] return ret
python
def iostat(zpool=None, sample_time=5, parsable=True): ''' Display I/O statistics for the given pools zpool : string optional name of storage pool sample_time : int seconds to capture data before output default a sample of 5 seconds is used parsable : boolean display data in pythonc values (True, False, Bytes,...) .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 Added ```parsable``` parameter that defaults to True CLI Example: .. code-block:: bash salt '*' zpool.iostat myzpool ''' ret = OrderedDict() ## get iostat output res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='iostat', flags=['-v'], target=[zpool, sample_time, 2] ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) # NOTE: command output for reference # ===================================================================== # capacity operations bandwidth # pool alloc free read write read write # ------------------------- ----- ----- ----- ----- ----- ----- # mypool 648G 1.18T 10 6 1.30M 817K # mirror 648G 1.18T 10 6 1.30M 817K # c0tXXXXCXXXXXXXXXXXd0 - - 9 5 1.29M 817K # c0tXXXXCXXXXXXXXXXXd0 - - 9 5 1.29M 817K # c0tXXXXCXXXXXXXXXXXd0 - - 9 5 1.29M 817K # ------------------------- ----- ----- ----- ----- ----- ----- # ===================================================================== ## parse iostat output # NOTE: hardcode the header # the double header line is hard to parse, we opt to # hardcode the header fields header = [ 'name', 'capacity-alloc', 'capacity-free', 'operations-read', 'operations-write', 'bandwith-read', 'bandwith-write', ] root_vdev = None vdev = None dev = None current_data = OrderedDict() for line in res['stdout'].splitlines(): # NOTE: skip header if line.strip() == '' or \ line.strip().split()[-1] in ['write', 'bandwidth']: continue # NOTE: reset pool on line separator if line.startswith('-') and line.endswith('-'): ret.update(current_data) current_data = OrderedDict() continue # NOTE: transform data into dict io_data = OrderedDict(list(zip( header, [x for x in line.strip().split(' ') if x not in ['']], ))) # NOTE: normalize values if parsable: # NOTE: raw numbers and pythonic types io_data = __utils__['zfs.from_auto_dict'](io_data) else: # NOTE: human readable zfs types io_data = __utils__['zfs.to_auto_dict'](io_data) # NOTE: store io_data in the proper location if line.startswith(' ' * 4): dev = io_data['name'] current_data[root_vdev][vdev][dev] = io_data elif line.startswith(' ' * 2): dev = None vdev = io_data['name'] current_data[root_vdev][vdev] = io_data else: dev = vdev = None root_vdev = io_data['name'] current_data[root_vdev] = io_data # NOTE: name already used as identifier, drop duplicate data del io_data['name'] return ret
[ "def", "iostat", "(", "zpool", "=", "None", ",", "sample_time", "=", "5", ",", "parsable", "=", "True", ")", ":", "ret", "=", "OrderedDict", "(", ")", "## get iostat output", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs...
Display I/O statistics for the given pools zpool : string optional name of storage pool sample_time : int seconds to capture data before output default a sample of 5 seconds is used parsable : boolean display data in pythonc values (True, False, Bytes,...) .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 Added ```parsable``` parameter that defaults to True CLI Example: .. code-block:: bash salt '*' zpool.iostat myzpool
[ "Display", "I", "/", "O", "statistics", "for", "the", "given", "pools" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L236-L345
train
saltstack/salt
salt/modules/zpool.py
list_
def list_(properties='size,alloc,free,cap,frag,health', zpool=None, parsable=True): ''' .. versionadded:: 2015.5.0 Return information about (all) storage pools zpool : string optional name of storage pool properties : string comma-separated list of properties to list parsable : boolean display numbers in parsable (exact) values .. versionadded:: 2018.3.0 .. note:: The ``name`` property will always be included, while the ``frag`` property will get removed if not available zpool : string optional zpool .. note:: Multiple storage pool can be provded as a space separated list CLI Example: .. code-block:: bash salt '*' zpool.list salt '*' zpool.list zpool=tank salt '*' zpool.list 'size,free' salt '*' zpool.list 'size,free' tank ''' ret = OrderedDict() ## update properties # NOTE: properties should be a list if not isinstance(properties, list): properties = properties.split(',') # NOTE: name should be first property while 'name' in properties: properties.remove('name') properties.insert(0, 'name') # NOTE: remove 'frags' if we don't have feature flags if not __utils__['zfs.has_feature_flags'](): while 'frag' in properties: properties.remove('frag') ## collect list output res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='list', flags=['-H'], opts={'-o': ','.join(properties)}, target=zpool ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) # NOTE: command output for reference # ======================================================================== # data 1992864825344 695955501056 1296909324288 34 11% ONLINE # ========================================================================= ## parse list output for line in res['stdout'].splitlines(): # NOTE: transform data into dict zpool_data = OrderedDict(list(zip( properties, line.strip().split('\t'), ))) # NOTE: normalize values if parsable: # NOTE: raw numbers and pythonic types zpool_data = __utils__['zfs.from_auto_dict'](zpool_data) else: # NOTE: human readable zfs types zpool_data = __utils__['zfs.to_auto_dict'](zpool_data) ret[zpool_data['name']] = zpool_data del ret[zpool_data['name']]['name'] return ret
python
def list_(properties='size,alloc,free,cap,frag,health', zpool=None, parsable=True): ''' .. versionadded:: 2015.5.0 Return information about (all) storage pools zpool : string optional name of storage pool properties : string comma-separated list of properties to list parsable : boolean display numbers in parsable (exact) values .. versionadded:: 2018.3.0 .. note:: The ``name`` property will always be included, while the ``frag`` property will get removed if not available zpool : string optional zpool .. note:: Multiple storage pool can be provded as a space separated list CLI Example: .. code-block:: bash salt '*' zpool.list salt '*' zpool.list zpool=tank salt '*' zpool.list 'size,free' salt '*' zpool.list 'size,free' tank ''' ret = OrderedDict() ## update properties # NOTE: properties should be a list if not isinstance(properties, list): properties = properties.split(',') # NOTE: name should be first property while 'name' in properties: properties.remove('name') properties.insert(0, 'name') # NOTE: remove 'frags' if we don't have feature flags if not __utils__['zfs.has_feature_flags'](): while 'frag' in properties: properties.remove('frag') ## collect list output res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='list', flags=['-H'], opts={'-o': ','.join(properties)}, target=zpool ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) # NOTE: command output for reference # ======================================================================== # data 1992864825344 695955501056 1296909324288 34 11% ONLINE # ========================================================================= ## parse list output for line in res['stdout'].splitlines(): # NOTE: transform data into dict zpool_data = OrderedDict(list(zip( properties, line.strip().split('\t'), ))) # NOTE: normalize values if parsable: # NOTE: raw numbers and pythonic types zpool_data = __utils__['zfs.from_auto_dict'](zpool_data) else: # NOTE: human readable zfs types zpool_data = __utils__['zfs.to_auto_dict'](zpool_data) ret[zpool_data['name']] = zpool_data del ret[zpool_data['name']]['name'] return ret
[ "def", "list_", "(", "properties", "=", "'size,alloc,free,cap,frag,health'", ",", "zpool", "=", "None", ",", "parsable", "=", "True", ")", ":", "ret", "=", "OrderedDict", "(", ")", "## update properties", "# NOTE: properties should be a list", "if", "not", "isinstan...
.. versionadded:: 2015.5.0 Return information about (all) storage pools zpool : string optional name of storage pool properties : string comma-separated list of properties to list parsable : boolean display numbers in parsable (exact) values .. versionadded:: 2018.3.0 .. note:: The ``name`` property will always be included, while the ``frag`` property will get removed if not available zpool : string optional zpool .. note:: Multiple storage pool can be provded as a space separated list CLI Example: .. code-block:: bash salt '*' zpool.list salt '*' zpool.list zpool=tank salt '*' zpool.list 'size,free' salt '*' zpool.list 'size,free' tank
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L348-L442
train
saltstack/salt
salt/modules/zpool.py
get
def get(zpool, prop=None, show_source=False, parsable=True): ''' .. versionadded:: 2016.3.0 Retrieves the given list of properties zpool : string Name of storage pool prop : string Optional name of property to retrieve show_source : boolean Show source of property parsable : boolean Display numbers in parsable (exact) values .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' zpool.get myzpool ''' ret = OrderedDict() value_properties = ['name', 'property', 'value', 'source'] ## collect get output res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='get', flags=['-H'], property_name=prop if prop else 'all', target=zpool, ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) # NOTE: command output for reference # ======================================================================== # ... # data mountpoint /data local # data compression off default # ... # ========================================================================= # parse get output for line in res['stdout'].splitlines(): # NOTE: transform data into dict prop_data = OrderedDict(list(zip( value_properties, [x for x in line.strip().split('\t') if x not in ['']], ))) # NOTE: older zfs does not have -o, fall back to manually stipping the name field del prop_data['name'] # NOTE: normalize values if parsable: # NOTE: raw numbers and pythonic types prop_data['value'] = __utils__['zfs.from_auto'](prop_data['property'], prop_data['value']) else: # NOTE: human readable zfs types prop_data['value'] = __utils__['zfs.to_auto'](prop_data['property'], prop_data['value']) # NOTE: show source if requested if show_source: ret[prop_data['property']] = prop_data del ret[prop_data['property']]['property'] else: ret[prop_data['property']] = prop_data['value'] return ret
python
def get(zpool, prop=None, show_source=False, parsable=True): ''' .. versionadded:: 2016.3.0 Retrieves the given list of properties zpool : string Name of storage pool prop : string Optional name of property to retrieve show_source : boolean Show source of property parsable : boolean Display numbers in parsable (exact) values .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' zpool.get myzpool ''' ret = OrderedDict() value_properties = ['name', 'property', 'value', 'source'] ## collect get output res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='get', flags=['-H'], property_name=prop if prop else 'all', target=zpool, ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) # NOTE: command output for reference # ======================================================================== # ... # data mountpoint /data local # data compression off default # ... # ========================================================================= # parse get output for line in res['stdout'].splitlines(): # NOTE: transform data into dict prop_data = OrderedDict(list(zip( value_properties, [x for x in line.strip().split('\t') if x not in ['']], ))) # NOTE: older zfs does not have -o, fall back to manually stipping the name field del prop_data['name'] # NOTE: normalize values if parsable: # NOTE: raw numbers and pythonic types prop_data['value'] = __utils__['zfs.from_auto'](prop_data['property'], prop_data['value']) else: # NOTE: human readable zfs types prop_data['value'] = __utils__['zfs.to_auto'](prop_data['property'], prop_data['value']) # NOTE: show source if requested if show_source: ret[prop_data['property']] = prop_data del ret[prop_data['property']]['property'] else: ret[prop_data['property']] = prop_data['value'] return ret
[ "def", "get", "(", "zpool", ",", "prop", "=", "None", ",", "show_source", "=", "False", ",", "parsable", "=", "True", ")", ":", "ret", "=", "OrderedDict", "(", ")", "value_properties", "=", "[", "'name'", ",", "'property'", ",", "'value'", ",", "'sourc...
.. versionadded:: 2016.3.0 Retrieves the given list of properties zpool : string Name of storage pool prop : string Optional name of property to retrieve show_source : boolean Show source of property parsable : boolean Display numbers in parsable (exact) values .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' zpool.get myzpool
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L445-L523
train
saltstack/salt
salt/modules/zpool.py
set
def set(zpool, prop, value): ''' Sets the given property on the specified pool zpool : string Name of storage pool prop : string Name of property to set value : string Value to set for the specified property .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.set myzpool readonly yes ''' ret = OrderedDict() # set property res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='set', property_name=prop, property_value=value, target=zpool, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'set')
python
def set(zpool, prop, value): ''' Sets the given property on the specified pool zpool : string Name of storage pool prop : string Name of property to set value : string Value to set for the specified property .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.set myzpool readonly yes ''' ret = OrderedDict() # set property res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='set', property_name=prop, property_value=value, target=zpool, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'set')
[ "def", "set", "(", "zpool", ",", "prop", ",", "value", ")", ":", "ret", "=", "OrderedDict", "(", ")", "# set property", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zpool_command'", "]", "(", "command", "=", "'set'", ",...
Sets the given property on the specified pool zpool : string Name of storage pool prop : string Name of property to set value : string Value to set for the specified property .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.set myzpool readonly yes
[ "Sets", "the", "given", "property", "on", "the", "specified", "pool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L526-L561
train
saltstack/salt
salt/modules/zpool.py
exists
def exists(zpool): ''' Check if a ZFS storage pool is active zpool : string Name of storage pool CLI Example: .. code-block:: bash salt '*' zpool.exists myzpool ''' # list for zpool # NOTE: retcode > 0 if zpool does not exists res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='list', target=zpool, ), python_shell=False, ignore_retcode=True, ) return res['retcode'] == 0
python
def exists(zpool): ''' Check if a ZFS storage pool is active zpool : string Name of storage pool CLI Example: .. code-block:: bash salt '*' zpool.exists myzpool ''' # list for zpool # NOTE: retcode > 0 if zpool does not exists res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='list', target=zpool, ), python_shell=False, ignore_retcode=True, ) return res['retcode'] == 0
[ "def", "exists", "(", "zpool", ")", ":", "# list for zpool", "# NOTE: retcode > 0 if zpool does not exists", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zpool_command'", "]", "(", "command", "=", "'list'", ",", "target", "=", "z...
Check if a ZFS storage pool is active zpool : string Name of storage pool CLI Example: .. code-block:: bash salt '*' zpool.exists myzpool
[ "Check", "if", "a", "ZFS", "storage", "pool", "is", "active" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L564-L589
train
saltstack/salt
salt/modules/zpool.py
destroy
def destroy(zpool, force=False): ''' Destroys a storage pool zpool : string Name of storage pool force : boolean Force destroy of pool CLI Example: .. code-block:: bash salt '*' zpool.destroy myzpool ''' # destroy zpool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='destroy', flags=['-f'] if force else None, target=zpool, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'destroyed')
python
def destroy(zpool, force=False): ''' Destroys a storage pool zpool : string Name of storage pool force : boolean Force destroy of pool CLI Example: .. code-block:: bash salt '*' zpool.destroy myzpool ''' # destroy zpool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='destroy', flags=['-f'] if force else None, target=zpool, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'destroyed')
[ "def", "destroy", "(", "zpool", ",", "force", "=", "False", ")", ":", "# destroy zpool", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zpool_command'", "]", "(", "command", "=", "'destroy'", ",", "flags", "=", "[", "'-f'",...
Destroys a storage pool zpool : string Name of storage pool force : boolean Force destroy of pool CLI Example: .. code-block:: bash salt '*' zpool.destroy myzpool
[ "Destroys", "a", "storage", "pool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L592-L619
train
saltstack/salt
salt/modules/zpool.py
scrub
def scrub(zpool, stop=False, pause=False): ''' Scrub a storage pool zpool : string Name of storage pool stop : boolean If ``True``, cancel ongoing scrub pause : boolean If ``True``, pause ongoing scrub .. versionadded:: 2018.3.0 .. note:: Pause is only available on recent versions of ZFS. If both ``pause`` and ``stop`` are ``True``, then ``stop`` will win. CLI Example: .. code-block:: bash salt '*' zpool.scrub myzpool ''' ## select correct action if stop: action = ['-s'] elif pause: action = ['-p'] else: action = None ## Scrub storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='scrub', flags=action, target=zpool, ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res, 'scrubbing') ret = OrderedDict() if stop or pause: ret['scrubbing'] = False else: ret['scrubbing'] = True return ret
python
def scrub(zpool, stop=False, pause=False): ''' Scrub a storage pool zpool : string Name of storage pool stop : boolean If ``True``, cancel ongoing scrub pause : boolean If ``True``, pause ongoing scrub .. versionadded:: 2018.3.0 .. note:: Pause is only available on recent versions of ZFS. If both ``pause`` and ``stop`` are ``True``, then ``stop`` will win. CLI Example: .. code-block:: bash salt '*' zpool.scrub myzpool ''' ## select correct action if stop: action = ['-s'] elif pause: action = ['-p'] else: action = None ## Scrub storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='scrub', flags=action, target=zpool, ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res, 'scrubbing') ret = OrderedDict() if stop or pause: ret['scrubbing'] = False else: ret['scrubbing'] = True return ret
[ "def", "scrub", "(", "zpool", ",", "stop", "=", "False", ",", "pause", "=", "False", ")", ":", "## select correct action", "if", "stop", ":", "action", "=", "[", "'-s'", "]", "elif", "pause", ":", "action", "=", "[", "'-p'", "]", "else", ":", "action...
Scrub a storage pool zpool : string Name of storage pool stop : boolean If ``True``, cancel ongoing scrub pause : boolean If ``True``, pause ongoing scrub .. versionadded:: 2018.3.0 .. note:: Pause is only available on recent versions of ZFS. If both ``pause`` and ``stop`` are ``True``, then ``stop`` will win. CLI Example: .. code-block:: bash salt '*' zpool.scrub myzpool
[ "Scrub", "a", "storage", "pool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L622-L677
train
saltstack/salt
salt/modules/zpool.py
create
def create(zpool, *vdevs, **kwargs): ''' .. versionadded:: 2015.5.0 Create a simple zpool, a mirrored zpool, a zpool having nested VDEVs, a hybrid zpool with cache, spare and log drives or a zpool with RAIDZ-1, RAIDZ-2 or RAIDZ-3 zpool : string Name of storage pool vdevs : string One or move devices force : boolean Forces use of vdevs, even if they appear in use or specify a conflicting replication level. mountpoint : string Sets the mount point for the root dataset altroot : string Equivalent to "-o cachefile=none,altroot=root" properties : dict Additional pool properties filesystem_properties : dict Additional filesystem properties createboot : boolean create a boot partition .. versionadded:: 2018.3.0 .. warning: This is only available on illumos and Solaris CLI Examples: .. code-block:: bash salt '*' zpool.create myzpool /path/to/vdev1 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 /path/to/vdev2 [...] [force=True|False] salt '*' zpool.create myzpool raidz1 /path/to/vdev1 /path/to/vdev2 raidz2 /path/to/vdev3 /path/to/vdev4 /path/to/vdev5 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 [...] mirror /path/to/vdev2 /path/to/vdev3 [...] [force=True|False] salt '*' zpool.create myhybridzpool mirror /tmp/file1 [...] log mirror /path/to/vdev1 [...] cache /path/to/vdev2 [...] spare /path/to/vdev3 [...] [force=True|False] .. note:: Zpool properties can be specified at the time of creation of the pool by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text properties="{'property1': 'value1', 'property2': 'value2'}" Filesystem properties can be specified at the time of creation of the pool by passing an additional argument called "filesystem_properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text filesystem_properties="{'property1': 'value1', 'property2': 'value2'}" Example: .. code-block:: bash salt '*' zpool.create myzpool /path/to/vdev1 [...] properties="{'property1': 'value1', 'property2': 'value2'}" CLI Example: .. code-block:: bash salt '*' zpool.create myzpool /path/to/vdev1 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 /path/to/vdev2 [...] [force=True|False] salt '*' zpool.create myzpool raidz1 /path/to/vdev1 /path/to/vdev2 raidz2 /path/to/vdev3 /path/to/vdev4 /path/to/vdev5 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 [...] mirror /path/to/vdev2 /path/to/vdev3 [...] [force=True|False] salt '*' zpool.create myhybridzpool mirror /tmp/file1 [...] log mirror /path/to/vdev1 [...] cache /path/to/vdev2 [...] spare /path/to/vdev3 [...] [force=True|False] ''' ## Configure pool # NOTE: initialize the defaults flags = [] opts = {} target = [] # NOTE: push pool and filesystem properties pool_properties = kwargs.get('properties', {}) filesystem_properties = kwargs.get('filesystem_properties', {}) # NOTE: set extra config based on kwargs if kwargs.get('force', False): flags.append('-f') if kwargs.get('createboot', False) or 'bootsize' in pool_properties: flags.append('-B') if kwargs.get('altroot', False): opts['-R'] = kwargs.get('altroot') if kwargs.get('mountpoint', False): opts['-m'] = kwargs.get('mountpoint') # NOTE: append the pool name and specifications target.append(zpool) target.extend(vdevs) ## Create storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='create', flags=flags, opts=opts, pool_properties=pool_properties, filesystem_properties=filesystem_properties, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'created') if ret['created']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
python
def create(zpool, *vdevs, **kwargs): ''' .. versionadded:: 2015.5.0 Create a simple zpool, a mirrored zpool, a zpool having nested VDEVs, a hybrid zpool with cache, spare and log drives or a zpool with RAIDZ-1, RAIDZ-2 or RAIDZ-3 zpool : string Name of storage pool vdevs : string One or move devices force : boolean Forces use of vdevs, even if they appear in use or specify a conflicting replication level. mountpoint : string Sets the mount point for the root dataset altroot : string Equivalent to "-o cachefile=none,altroot=root" properties : dict Additional pool properties filesystem_properties : dict Additional filesystem properties createboot : boolean create a boot partition .. versionadded:: 2018.3.0 .. warning: This is only available on illumos and Solaris CLI Examples: .. code-block:: bash salt '*' zpool.create myzpool /path/to/vdev1 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 /path/to/vdev2 [...] [force=True|False] salt '*' zpool.create myzpool raidz1 /path/to/vdev1 /path/to/vdev2 raidz2 /path/to/vdev3 /path/to/vdev4 /path/to/vdev5 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 [...] mirror /path/to/vdev2 /path/to/vdev3 [...] [force=True|False] salt '*' zpool.create myhybridzpool mirror /tmp/file1 [...] log mirror /path/to/vdev1 [...] cache /path/to/vdev2 [...] spare /path/to/vdev3 [...] [force=True|False] .. note:: Zpool properties can be specified at the time of creation of the pool by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text properties="{'property1': 'value1', 'property2': 'value2'}" Filesystem properties can be specified at the time of creation of the pool by passing an additional argument called "filesystem_properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text filesystem_properties="{'property1': 'value1', 'property2': 'value2'}" Example: .. code-block:: bash salt '*' zpool.create myzpool /path/to/vdev1 [...] properties="{'property1': 'value1', 'property2': 'value2'}" CLI Example: .. code-block:: bash salt '*' zpool.create myzpool /path/to/vdev1 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 /path/to/vdev2 [...] [force=True|False] salt '*' zpool.create myzpool raidz1 /path/to/vdev1 /path/to/vdev2 raidz2 /path/to/vdev3 /path/to/vdev4 /path/to/vdev5 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 [...] mirror /path/to/vdev2 /path/to/vdev3 [...] [force=True|False] salt '*' zpool.create myhybridzpool mirror /tmp/file1 [...] log mirror /path/to/vdev1 [...] cache /path/to/vdev2 [...] spare /path/to/vdev3 [...] [force=True|False] ''' ## Configure pool # NOTE: initialize the defaults flags = [] opts = {} target = [] # NOTE: push pool and filesystem properties pool_properties = kwargs.get('properties', {}) filesystem_properties = kwargs.get('filesystem_properties', {}) # NOTE: set extra config based on kwargs if kwargs.get('force', False): flags.append('-f') if kwargs.get('createboot', False) or 'bootsize' in pool_properties: flags.append('-B') if kwargs.get('altroot', False): opts['-R'] = kwargs.get('altroot') if kwargs.get('mountpoint', False): opts['-m'] = kwargs.get('mountpoint') # NOTE: append the pool name and specifications target.append(zpool) target.extend(vdevs) ## Create storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='create', flags=flags, opts=opts, pool_properties=pool_properties, filesystem_properties=filesystem_properties, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'created') if ret['created']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
[ "def", "create", "(", "zpool", ",", "*", "vdevs", ",", "*", "*", "kwargs", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "opts", "=", "{", "}", "target", "=", "[", "]", "# NOTE: push pool and filesystem properties", ...
.. versionadded:: 2015.5.0 Create a simple zpool, a mirrored zpool, a zpool having nested VDEVs, a hybrid zpool with cache, spare and log drives or a zpool with RAIDZ-1, RAIDZ-2 or RAIDZ-3 zpool : string Name of storage pool vdevs : string One or move devices force : boolean Forces use of vdevs, even if they appear in use or specify a conflicting replication level. mountpoint : string Sets the mount point for the root dataset altroot : string Equivalent to "-o cachefile=none,altroot=root" properties : dict Additional pool properties filesystem_properties : dict Additional filesystem properties createboot : boolean create a boot partition .. versionadded:: 2018.3.0 .. warning: This is only available on illumos and Solaris CLI Examples: .. code-block:: bash salt '*' zpool.create myzpool /path/to/vdev1 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 /path/to/vdev2 [...] [force=True|False] salt '*' zpool.create myzpool raidz1 /path/to/vdev1 /path/to/vdev2 raidz2 /path/to/vdev3 /path/to/vdev4 /path/to/vdev5 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 [...] mirror /path/to/vdev2 /path/to/vdev3 [...] [force=True|False] salt '*' zpool.create myhybridzpool mirror /tmp/file1 [...] log mirror /path/to/vdev1 [...] cache /path/to/vdev2 [...] spare /path/to/vdev3 [...] [force=True|False] .. note:: Zpool properties can be specified at the time of creation of the pool by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text properties="{'property1': 'value1', 'property2': 'value2'}" Filesystem properties can be specified at the time of creation of the pool by passing an additional argument called "filesystem_properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text filesystem_properties="{'property1': 'value1', 'property2': 'value2'}" Example: .. code-block:: bash salt '*' zpool.create myzpool /path/to/vdev1 [...] properties="{'property1': 'value1', 'property2': 'value2'}" CLI Example: .. code-block:: bash salt '*' zpool.create myzpool /path/to/vdev1 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 /path/to/vdev2 [...] [force=True|False] salt '*' zpool.create myzpool raidz1 /path/to/vdev1 /path/to/vdev2 raidz2 /path/to/vdev3 /path/to/vdev4 /path/to/vdev5 [...] [force=True|False] salt '*' zpool.create myzpool mirror /path/to/vdev1 [...] mirror /path/to/vdev2 /path/to/vdev3 [...] [force=True|False] salt '*' zpool.create myhybridzpool mirror /tmp/file1 [...] log mirror /path/to/vdev1 [...] cache /path/to/vdev2 [...] spare /path/to/vdev3 [...] [force=True|False]
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L680-L807
train
saltstack/salt
salt/modules/zpool.py
add
def add(zpool, *vdevs, **kwargs): ''' Add the specified vdev\'s to the given storage pool zpool : string Name of storage pool vdevs : string One or more devices force : boolean Forces use of device CLI Example: .. code-block:: bash salt '*' zpool.add myzpool /path/to/vdev1 /path/to/vdev2 [...] ''' ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config based on kwargs if kwargs.get('force', False): flags.append('-f') # NOTE: append the pool name and specifications target.append(zpool) target.extend(vdevs) ## Update storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='add', flags=flags, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'added') if ret['added']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
python
def add(zpool, *vdevs, **kwargs): ''' Add the specified vdev\'s to the given storage pool zpool : string Name of storage pool vdevs : string One or more devices force : boolean Forces use of device CLI Example: .. code-block:: bash salt '*' zpool.add myzpool /path/to/vdev1 /path/to/vdev2 [...] ''' ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config based on kwargs if kwargs.get('force', False): flags.append('-f') # NOTE: append the pool name and specifications target.append(zpool) target.extend(vdevs) ## Update storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='add', flags=flags, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'added') if ret['added']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
[ "def", "add", "(", "zpool", ",", "*", "vdevs", ",", "*", "*", "kwargs", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "target", "=", "[", "]", "# NOTE: set extra config based on kwargs", "if", "kwargs", ".", "get", "...
Add the specified vdev\'s to the given storage pool zpool : string Name of storage pool vdevs : string One or more devices force : boolean Forces use of device CLI Example: .. code-block:: bash salt '*' zpool.add myzpool /path/to/vdev1 /path/to/vdev2 [...]
[ "Add", "the", "specified", "vdev", "\\", "s", "to", "the", "given", "storage", "pool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L810-L860
train
saltstack/salt
salt/modules/zpool.py
attach
def attach(zpool, device, new_device, force=False): ''' Attach specified device to zpool zpool : string Name of storage pool device : string Existing device name too new_device : string New device name (to be attached to ``device``) force : boolean Forces use of device CLI Example: .. code-block:: bash salt '*' zpool.attach myzpool /path/to/vdev1 /path/to/vdev2 [...] ''' ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config if force: flags.append('-f') # NOTE: append the pool name and specifications target.append(zpool) target.append(device) target.append(new_device) ## Update storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='attach', flags=flags, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'attached') if ret['attached']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
python
def attach(zpool, device, new_device, force=False): ''' Attach specified device to zpool zpool : string Name of storage pool device : string Existing device name too new_device : string New device name (to be attached to ``device``) force : boolean Forces use of device CLI Example: .. code-block:: bash salt '*' zpool.attach myzpool /path/to/vdev1 /path/to/vdev2 [...] ''' ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config if force: flags.append('-f') # NOTE: append the pool name and specifications target.append(zpool) target.append(device) target.append(new_device) ## Update storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='attach', flags=flags, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'attached') if ret['attached']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
[ "def", "attach", "(", "zpool", ",", "device", ",", "new_device", ",", "force", "=", "False", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "target", "=", "[", "]", "# NOTE: set extra config", "if", "force", ":", "fla...
Attach specified device to zpool zpool : string Name of storage pool device : string Existing device name too new_device : string New device name (to be attached to ``device``) force : boolean Forces use of device CLI Example: .. code-block:: bash salt '*' zpool.attach myzpool /path/to/vdev1 /path/to/vdev2 [...]
[ "Attach", "specified", "device", "to", "zpool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L863-L917
train
saltstack/salt
salt/modules/zpool.py
detach
def detach(zpool, device): ''' Detach specified device to zpool zpool : string Name of storage pool device : string Device to detach CLI Example: .. code-block:: bash salt '*' zpool.detach myzpool /path/to/vdev1 ''' ## Update storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='detach', target=[zpool, device], ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'detatched') if ret['detatched']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
python
def detach(zpool, device): ''' Detach specified device to zpool zpool : string Name of storage pool device : string Device to detach CLI Example: .. code-block:: bash salt '*' zpool.detach myzpool /path/to/vdev1 ''' ## Update storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='detach', target=[zpool, device], ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'detatched') if ret['detatched']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
[ "def", "detach", "(", "zpool", ",", "device", ")", ":", "## Update storage pool", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zpool_command'", "]", "(", "command", "=", "'detach'", ",", "target", "=", "[", "zpool", ",", ...
Detach specified device to zpool zpool : string Name of storage pool device : string Device to detach CLI Example: .. code-block:: bash salt '*' zpool.detach myzpool /path/to/vdev1
[ "Detach", "specified", "device", "to", "zpool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L920-L953
train
saltstack/salt
salt/modules/zpool.py
split
def split(zpool, newzpool, **kwargs): ''' .. versionadded:: 2018.3.0 Splits devices off pool creating newpool. .. note:: All vdevs in pool must be mirrors. At the time of the split, ``newzpool`` will be a replica of ``zpool``. After splitting, do not forget to import the new pool! zpool : string Name of storage pool newzpool : string Name of new storage pool mountpoint : string Sets the mount point for the root dataset altroot : string Sets altroot for newzpool properties : dict Additional pool properties for newzpool CLI Examples: .. code-block:: bash salt '*' zpool.split datamirror databackup salt '*' zpool.split datamirror databackup altroot=/backup .. note:: Zpool properties can be specified at the time of creation of the pool by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text properties="{'property1': 'value1', 'property2': 'value2'}" Example: .. code-block:: bash salt '*' zpool.split datamirror databackup properties="{'readonly': 'on'}" CLI Example: .. code-block:: bash salt '*' zpool.split datamirror databackup salt '*' zpool.split datamirror databackup altroot=/backup ''' ## Configure pool # NOTE: initialize the defaults opts = {} # NOTE: push pool and filesystem properties pool_properties = kwargs.get('properties', {}) # NOTE: set extra config based on kwargs if kwargs.get('altroot', False): opts['-R'] = kwargs.get('altroot') ## Split storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='split', opts=opts, pool_properties=pool_properties, target=[zpool, newzpool], ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'split')
python
def split(zpool, newzpool, **kwargs): ''' .. versionadded:: 2018.3.0 Splits devices off pool creating newpool. .. note:: All vdevs in pool must be mirrors. At the time of the split, ``newzpool`` will be a replica of ``zpool``. After splitting, do not forget to import the new pool! zpool : string Name of storage pool newzpool : string Name of new storage pool mountpoint : string Sets the mount point for the root dataset altroot : string Sets altroot for newzpool properties : dict Additional pool properties for newzpool CLI Examples: .. code-block:: bash salt '*' zpool.split datamirror databackup salt '*' zpool.split datamirror databackup altroot=/backup .. note:: Zpool properties can be specified at the time of creation of the pool by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text properties="{'property1': 'value1', 'property2': 'value2'}" Example: .. code-block:: bash salt '*' zpool.split datamirror databackup properties="{'readonly': 'on'}" CLI Example: .. code-block:: bash salt '*' zpool.split datamirror databackup salt '*' zpool.split datamirror databackup altroot=/backup ''' ## Configure pool # NOTE: initialize the defaults opts = {} # NOTE: push pool and filesystem properties pool_properties = kwargs.get('properties', {}) # NOTE: set extra config based on kwargs if kwargs.get('altroot', False): opts['-R'] = kwargs.get('altroot') ## Split storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='split', opts=opts, pool_properties=pool_properties, target=[zpool, newzpool], ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'split')
[ "def", "split", "(", "zpool", ",", "newzpool", ",", "*", "*", "kwargs", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "opts", "=", "{", "}", "# NOTE: push pool and filesystem properties", "pool_properties", "=", "kwargs", ".", "get", "(", "'prope...
.. versionadded:: 2018.3.0 Splits devices off pool creating newpool. .. note:: All vdevs in pool must be mirrors. At the time of the split, ``newzpool`` will be a replica of ``zpool``. After splitting, do not forget to import the new pool! zpool : string Name of storage pool newzpool : string Name of new storage pool mountpoint : string Sets the mount point for the root dataset altroot : string Sets altroot for newzpool properties : dict Additional pool properties for newzpool CLI Examples: .. code-block:: bash salt '*' zpool.split datamirror databackup salt '*' zpool.split datamirror databackup altroot=/backup .. note:: Zpool properties can be specified at the time of creation of the pool by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text properties="{'property1': 'value1', 'property2': 'value2'}" Example: .. code-block:: bash salt '*' zpool.split datamirror databackup properties="{'readonly': 'on'}" CLI Example: .. code-block:: bash salt '*' zpool.split datamirror databackup salt '*' zpool.split datamirror databackup altroot=/backup
[ "..", "versionadded", "::", "2018", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L956-L1038
train
saltstack/salt
salt/modules/zpool.py
replace
def replace(zpool, old_device, new_device=None, force=False): ''' Replaces ``old_device`` with ``new_device`` .. note:: This is equivalent to attaching ``new_device``, waiting for it to resilver, and then detaching ``old_device``. The size of ``new_device`` must be greater than or equal to the minimum size of all the devices in a mirror or raidz configuration. zpool : string Name of storage pool old_device : string Old device to replace new_device : string Optional new device force : boolean Forces use of new_device, even if its appears to be in use. CLI Example: .. code-block:: bash salt '*' zpool.replace myzpool /path/to/vdev1 /path/to/vdev2 ''' ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config if force: flags.append('-f') # NOTE: append the pool name and specifications target.append(zpool) target.append(old_device) if new_device: target.append(new_device) ## Replace device res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='replace', flags=flags, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'replaced') if ret['replaced']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
python
def replace(zpool, old_device, new_device=None, force=False): ''' Replaces ``old_device`` with ``new_device`` .. note:: This is equivalent to attaching ``new_device``, waiting for it to resilver, and then detaching ``old_device``. The size of ``new_device`` must be greater than or equal to the minimum size of all the devices in a mirror or raidz configuration. zpool : string Name of storage pool old_device : string Old device to replace new_device : string Optional new device force : boolean Forces use of new_device, even if its appears to be in use. CLI Example: .. code-block:: bash salt '*' zpool.replace myzpool /path/to/vdev1 /path/to/vdev2 ''' ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config if force: flags.append('-f') # NOTE: append the pool name and specifications target.append(zpool) target.append(old_device) if new_device: target.append(new_device) ## Replace device res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='replace', flags=flags, target=target, ), python_shell=False, ) ret = __utils__['zfs.parse_command_result'](res, 'replaced') if ret['replaced']: ## NOTE: lookup zpool status for vdev config ret['vdevs'] = _clean_vdev_config( __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool], ) return ret
[ "def", "replace", "(", "zpool", ",", "old_device", ",", "new_device", "=", "None", ",", "force", "=", "False", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "target", "=", "[", "]", "# NOTE: set extra config", "if", ...
Replaces ``old_device`` with ``new_device`` .. note:: This is equivalent to attaching ``new_device``, waiting for it to resilver, and then detaching ``old_device``. The size of ``new_device`` must be greater than or equal to the minimum size of all the devices in a mirror or raidz configuration. zpool : string Name of storage pool old_device : string Old device to replace new_device : string Optional new device force : boolean Forces use of new_device, even if its appears to be in use. CLI Example: .. code-block:: bash salt '*' zpool.replace myzpool /path/to/vdev1 /path/to/vdev2
[ "Replaces", "old_device", "with", "new_device" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1041-L1104
train
saltstack/salt
salt/modules/zpool.py
create_file_vdev
def create_file_vdev(size, *vdevs): ''' Creates file based virtual devices for a zpool CLI Example: .. code-block:: bash salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...] .. note:: Depending on file size, the above command may take a while to return. ''' ret = OrderedDict() err = OrderedDict() _mkfile_cmd = salt.utils.path.which('mkfile') for vdev in vdevs: if os.path.isfile(vdev): ret[vdev] = 'existed' else: res = __salt__['cmd.run_all']( '{mkfile} {size} {vdev}'.format( mkfile=_mkfile_cmd, size=size, vdev=vdev, ), python_shell=False, ) if res['retcode'] != 0: if 'stderr' in res and ':' in res['stderr']: ret[vdev] = 'failed' err[vdev] = ":".join(res['stderr'].strip().split(':')[1:]) else: ret[vdev] = 'created' if err: ret['error'] = err return ret
python
def create_file_vdev(size, *vdevs): ''' Creates file based virtual devices for a zpool CLI Example: .. code-block:: bash salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...] .. note:: Depending on file size, the above command may take a while to return. ''' ret = OrderedDict() err = OrderedDict() _mkfile_cmd = salt.utils.path.which('mkfile') for vdev in vdevs: if os.path.isfile(vdev): ret[vdev] = 'existed' else: res = __salt__['cmd.run_all']( '{mkfile} {size} {vdev}'.format( mkfile=_mkfile_cmd, size=size, vdev=vdev, ), python_shell=False, ) if res['retcode'] != 0: if 'stderr' in res and ':' in res['stderr']: ret[vdev] = 'failed' err[vdev] = ":".join(res['stderr'].strip().split(':')[1:]) else: ret[vdev] = 'created' if err: ret['error'] = err return ret
[ "def", "create_file_vdev", "(", "size", ",", "*", "vdevs", ")", ":", "ret", "=", "OrderedDict", "(", ")", "err", "=", "OrderedDict", "(", ")", "_mkfile_cmd", "=", "salt", ".", "utils", ".", "path", ".", "which", "(", "'mkfile'", ")", "for", "vdev", "...
Creates file based virtual devices for a zpool CLI Example: .. code-block:: bash salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...] .. note:: Depending on file size, the above command may take a while to return.
[ "Creates", "file", "based", "virtual", "devices", "for", "a", "zpool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1108-L1148
train
saltstack/salt
salt/modules/zpool.py
export
def export(*pools, **kwargs): ''' .. versionadded:: 2015.5.0 Export storage pools pools : string One or more storage pools to export force : boolean Force export of storage pools CLI Example: .. code-block:: bash salt '*' zpool.export myzpool ... [force=True|False] salt '*' zpool.export myzpool2 myzpool2 ... [force=True|False] ''' ## Configure pool # NOTE: initialize the defaults flags = [] targets = [] # NOTE: set extra config based on kwargs if kwargs.get('force', False): flags.append('-f') # NOTE: append the pool name and specifications targets = list(pools) ## Export pools res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='export', flags=flags, target=targets, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'exported')
python
def export(*pools, **kwargs): ''' .. versionadded:: 2015.5.0 Export storage pools pools : string One or more storage pools to export force : boolean Force export of storage pools CLI Example: .. code-block:: bash salt '*' zpool.export myzpool ... [force=True|False] salt '*' zpool.export myzpool2 myzpool2 ... [force=True|False] ''' ## Configure pool # NOTE: initialize the defaults flags = [] targets = [] # NOTE: set extra config based on kwargs if kwargs.get('force', False): flags.append('-f') # NOTE: append the pool name and specifications targets = list(pools) ## Export pools res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='export', flags=flags, target=targets, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'exported')
[ "def", "export", "(", "*", "pools", ",", "*", "*", "kwargs", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "targets", "=", "[", "]", "# NOTE: set extra config based on kwargs", "if", "kwargs", ".", "get", "(", "'force'...
.. versionadded:: 2015.5.0 Export storage pools pools : string One or more storage pools to export force : boolean Force export of storage pools CLI Example: .. code-block:: bash salt '*' zpool.export myzpool ... [force=True|False] salt '*' zpool.export myzpool2 myzpool2 ... [force=True|False]
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1151-L1193
train
saltstack/salt
salt/modules/zpool.py
import_
def import_(zpool=None, new_name=None, **kwargs): ''' .. versionadded:: 2015.5.0 Import storage pools or list pools available for import zpool : string Optional name of storage pool new_name : string Optional new name for the storage pool mntopts : string Comma-separated list of mount options to use when mounting datasets within the pool. force : boolean Forces import, even if the pool appears to be potentially active. altroot : string Equivalent to "-o cachefile=none,altroot=root" dir : string Searches for devices or files in dir, multiple dirs can be specified as follows: ``dir="dir1,dir2"`` no_mount : boolean Import the pool without mounting any file systems. only_destroyed : boolean Imports destroyed pools only. This also sets ``force=True``. recovery : bool|str false: do not try to recovery broken pools true: try to recovery the pool by rolling back the latest transactions test: check if a pool can be recovered, but don't import it nolog: allow import without log device, recent transactions might be lost .. note:: If feature flags are not support this forced to the default of 'false' .. warning:: When recovery is set to 'test' the result will be have imported set to True if the pool can be imported. The pool might also be imported if the pool was not broken to begin with. properties : dict Additional pool properties .. note:: Zpool properties can be specified at the time of creation of the pool by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text properties="{'property1': 'value1', 'property2': 'value2'}" CLI Example: .. code-block:: bash salt '*' zpool.import [force=True|False] salt '*' zpool.import myzpool [mynewzpool] [force=True|False] salt '*' zpool.import myzpool dir='/tmp' ''' ## Configure pool # NOTE: initialize the defaults flags = [] opts = {} target = [] # NOTE: push pool and filesystem properties pool_properties = kwargs.get('properties', {}) # NOTE: set extra config based on kwargs if kwargs.get('force', False) or kwargs.get('only_destroyed', False): flags.append('-f') if kwargs.get('only_destroyed', False): flags.append('-D') if kwargs.get('no_mount', False): flags.append('-N') if kwargs.get('altroot', False): opts['-R'] = kwargs.get('altroot') if kwargs.get('mntopts', False): # NOTE: -o is used for both mount options and pool properties! # ```-o nodevices,noexec,nosetuid,ro``` vs ```-o prop=val``` opts['-o'] = kwargs.get('mntopts') if kwargs.get('dir', False): opts['-d'] = kwargs.get('dir').split(',') if kwargs.get('recovery', False) and __utils__['zfs.has_feature_flags'](): recovery = kwargs.get('recovery') if recovery in [True, 'test']: flags.append('-F') if recovery == 'test': flags.append('-n') if recovery == 'nolog': flags.append('-m') # NOTE: append the pool name and specifications if zpool: target.append(zpool) target.append(new_name) else: flags.append('-a') ## Import storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='import', flags=flags, opts=opts, pool_properties=pool_properties, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'imported')
python
def import_(zpool=None, new_name=None, **kwargs): ''' .. versionadded:: 2015.5.0 Import storage pools or list pools available for import zpool : string Optional name of storage pool new_name : string Optional new name for the storage pool mntopts : string Comma-separated list of mount options to use when mounting datasets within the pool. force : boolean Forces import, even if the pool appears to be potentially active. altroot : string Equivalent to "-o cachefile=none,altroot=root" dir : string Searches for devices or files in dir, multiple dirs can be specified as follows: ``dir="dir1,dir2"`` no_mount : boolean Import the pool without mounting any file systems. only_destroyed : boolean Imports destroyed pools only. This also sets ``force=True``. recovery : bool|str false: do not try to recovery broken pools true: try to recovery the pool by rolling back the latest transactions test: check if a pool can be recovered, but don't import it nolog: allow import without log device, recent transactions might be lost .. note:: If feature flags are not support this forced to the default of 'false' .. warning:: When recovery is set to 'test' the result will be have imported set to True if the pool can be imported. The pool might also be imported if the pool was not broken to begin with. properties : dict Additional pool properties .. note:: Zpool properties can be specified at the time of creation of the pool by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text properties="{'property1': 'value1', 'property2': 'value2'}" CLI Example: .. code-block:: bash salt '*' zpool.import [force=True|False] salt '*' zpool.import myzpool [mynewzpool] [force=True|False] salt '*' zpool.import myzpool dir='/tmp' ''' ## Configure pool # NOTE: initialize the defaults flags = [] opts = {} target = [] # NOTE: push pool and filesystem properties pool_properties = kwargs.get('properties', {}) # NOTE: set extra config based on kwargs if kwargs.get('force', False) or kwargs.get('only_destroyed', False): flags.append('-f') if kwargs.get('only_destroyed', False): flags.append('-D') if kwargs.get('no_mount', False): flags.append('-N') if kwargs.get('altroot', False): opts['-R'] = kwargs.get('altroot') if kwargs.get('mntopts', False): # NOTE: -o is used for both mount options and pool properties! # ```-o nodevices,noexec,nosetuid,ro``` vs ```-o prop=val``` opts['-o'] = kwargs.get('mntopts') if kwargs.get('dir', False): opts['-d'] = kwargs.get('dir').split(',') if kwargs.get('recovery', False) and __utils__['zfs.has_feature_flags'](): recovery = kwargs.get('recovery') if recovery in [True, 'test']: flags.append('-F') if recovery == 'test': flags.append('-n') if recovery == 'nolog': flags.append('-m') # NOTE: append the pool name and specifications if zpool: target.append(zpool) target.append(new_name) else: flags.append('-a') ## Import storage pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='import', flags=flags, opts=opts, pool_properties=pool_properties, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'imported')
[ "def", "import_", "(", "zpool", "=", "None", ",", "new_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "opts", "=", "{", "}", "target", "=", "[", "]", "# NOTE: push pool...
.. versionadded:: 2015.5.0 Import storage pools or list pools available for import zpool : string Optional name of storage pool new_name : string Optional new name for the storage pool mntopts : string Comma-separated list of mount options to use when mounting datasets within the pool. force : boolean Forces import, even if the pool appears to be potentially active. altroot : string Equivalent to "-o cachefile=none,altroot=root" dir : string Searches for devices or files in dir, multiple dirs can be specified as follows: ``dir="dir1,dir2"`` no_mount : boolean Import the pool without mounting any file systems. only_destroyed : boolean Imports destroyed pools only. This also sets ``force=True``. recovery : bool|str false: do not try to recovery broken pools true: try to recovery the pool by rolling back the latest transactions test: check if a pool can be recovered, but don't import it nolog: allow import without log device, recent transactions might be lost .. note:: If feature flags are not support this forced to the default of 'false' .. warning:: When recovery is set to 'test' the result will be have imported set to True if the pool can be imported. The pool might also be imported if the pool was not broken to begin with. properties : dict Additional pool properties .. note:: Zpool properties can be specified at the time of creation of the pool by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary: .. code-block:: text properties="{'property1': 'value1', 'property2': 'value2'}" CLI Example: .. code-block:: bash salt '*' zpool.import [force=True|False] salt '*' zpool.import myzpool [mynewzpool] [force=True|False] salt '*' zpool.import myzpool dir='/tmp'
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1196-L1316
train
saltstack/salt
salt/modules/zpool.py
online
def online(zpool, *vdevs, **kwargs): ''' .. versionadded:: 2015.5.0 Ensure that the specified devices are online zpool : string name of storage pool vdevs : string one or more devices expand : boolean Expand the device to use all available space. .. note:: If the device is part of a mirror or raidz then all devices must be expanded before the new space will become available to the pool. CLI Example: .. code-block:: bash salt '*' zpool.online myzpool /path/to/vdev1 [...] ''' ## Configure pool # default options flags = [] target = [] # set flags and options if kwargs.get('expand', False): flags.append('-e') target.append(zpool) if vdevs: target.extend(vdevs) ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config based on kwargs if kwargs.get('expand', False): flags.append('-e') # NOTE: append the pool name and specifications target.append(zpool) target.extend(vdevs) ## Bring online device res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='online', flags=flags, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'onlined')
python
def online(zpool, *vdevs, **kwargs): ''' .. versionadded:: 2015.5.0 Ensure that the specified devices are online zpool : string name of storage pool vdevs : string one or more devices expand : boolean Expand the device to use all available space. .. note:: If the device is part of a mirror or raidz then all devices must be expanded before the new space will become available to the pool. CLI Example: .. code-block:: bash salt '*' zpool.online myzpool /path/to/vdev1 [...] ''' ## Configure pool # default options flags = [] target = [] # set flags and options if kwargs.get('expand', False): flags.append('-e') target.append(zpool) if vdevs: target.extend(vdevs) ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config based on kwargs if kwargs.get('expand', False): flags.append('-e') # NOTE: append the pool name and specifications target.append(zpool) target.extend(vdevs) ## Bring online device res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='online', flags=flags, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'onlined')
[ "def", "online", "(", "zpool", ",", "*", "vdevs", ",", "*", "*", "kwargs", ")", ":", "## Configure pool", "# default options", "flags", "=", "[", "]", "target", "=", "[", "]", "# set flags and options", "if", "kwargs", ".", "get", "(", "'expand'", ",", "...
.. versionadded:: 2015.5.0 Ensure that the specified devices are online zpool : string name of storage pool vdevs : string one or more devices expand : boolean Expand the device to use all available space. .. note:: If the device is part of a mirror or raidz then all devices must be expanded before the new space will become available to the pool. CLI Example: .. code-block:: bash salt '*' zpool.online myzpool /path/to/vdev1 [...]
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1319-L1381
train
saltstack/salt
salt/modules/zpool.py
offline
def offline(zpool, *vdevs, **kwargs): ''' .. versionadded:: 2015.5.0 Ensure that the specified devices are offline .. warning:: By default, the ``OFFLINE`` state is persistent. The device remains offline when the system is rebooted. To temporarily take a device offline, use ``temporary=True``. zpool : string name of storage pool vdevs : string One or more devices temporary : boolean Enable temporarily offline CLI Example: .. code-block:: bash salt '*' zpool.offline myzpool /path/to/vdev1 [...] [temporary=True|False] ''' ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config based on kwargs if kwargs.get('temporary', False): flags.append('-t') # NOTE: append the pool name and specifications target.append(zpool) target.extend(vdevs) ## Take a device offline res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='offline', flags=flags, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'offlined')
python
def offline(zpool, *vdevs, **kwargs): ''' .. versionadded:: 2015.5.0 Ensure that the specified devices are offline .. warning:: By default, the ``OFFLINE`` state is persistent. The device remains offline when the system is rebooted. To temporarily take a device offline, use ``temporary=True``. zpool : string name of storage pool vdevs : string One or more devices temporary : boolean Enable temporarily offline CLI Example: .. code-block:: bash salt '*' zpool.offline myzpool /path/to/vdev1 [...] [temporary=True|False] ''' ## Configure pool # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config based on kwargs if kwargs.get('temporary', False): flags.append('-t') # NOTE: append the pool name and specifications target.append(zpool) target.extend(vdevs) ## Take a device offline res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='offline', flags=flags, target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'offlined')
[ "def", "offline", "(", "zpool", ",", "*", "vdevs", ",", "*", "*", "kwargs", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "target", "=", "[", "]", "# NOTE: set extra config based on kwargs", "if", "kwargs", ".", "get",...
.. versionadded:: 2015.5.0 Ensure that the specified devices are offline .. warning:: By default, the ``OFFLINE`` state is persistent. The device remains offline when the system is rebooted. To temporarily take a device offline, use ``temporary=True``. zpool : string name of storage pool vdevs : string One or more devices temporary : boolean Enable temporarily offline CLI Example: .. code-block:: bash salt '*' zpool.offline myzpool /path/to/vdev1 [...] [temporary=True|False]
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1384-L1435
train
saltstack/salt
salt/modules/zpool.py
labelclear
def labelclear(device, force=False): ''' .. versionadded:: 2018.3.0 Removes ZFS label information from the specified device device : string Device name; must not be part of an active pool configuration. force : boolean Treat exported or foreign devices as inactive CLI Example: .. code-block:: bash salt '*' zpool.labelclear /path/to/dev ''' ## clear label for all specified device res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='labelclear', flags=['-f'] if force else None, target=device, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'labelcleared')
python
def labelclear(device, force=False): ''' .. versionadded:: 2018.3.0 Removes ZFS label information from the specified device device : string Device name; must not be part of an active pool configuration. force : boolean Treat exported or foreign devices as inactive CLI Example: .. code-block:: bash salt '*' zpool.labelclear /path/to/dev ''' ## clear label for all specified device res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='labelclear', flags=['-f'] if force else None, target=device, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'labelcleared')
[ "def", "labelclear", "(", "device", ",", "force", "=", "False", ")", ":", "## clear label for all specified device", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zpool_command'", "]", "(", "command", "=", "'labelclear'", ",", "...
.. versionadded:: 2018.3.0 Removes ZFS label information from the specified device device : string Device name; must not be part of an active pool configuration. force : boolean Treat exported or foreign devices as inactive CLI Example: .. code-block:: bash salt '*' zpool.labelclear /path/to/dev
[ "..", "versionadded", "::", "2018", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1438-L1467
train
saltstack/salt
salt/modules/zpool.py
clear
def clear(zpool, device=None): ''' Clears device errors in a pool. .. warning:: The device must not be part of an active pool configuration. zpool : string name of storage pool device : string (optional) specific device to clear .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt '*' zpool.clear mypool salt '*' zpool.clear mypool /path/to/dev ''' ## Configure pool # NOTE: initialize the defaults target = [] # NOTE: append the pool name and specifications target.append(zpool) target.append(device) ## clear storage pool errors res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='clear', target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'cleared')
python
def clear(zpool, device=None): ''' Clears device errors in a pool. .. warning:: The device must not be part of an active pool configuration. zpool : string name of storage pool device : string (optional) specific device to clear .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt '*' zpool.clear mypool salt '*' zpool.clear mypool /path/to/dev ''' ## Configure pool # NOTE: initialize the defaults target = [] # NOTE: append the pool name and specifications target.append(zpool) target.append(device) ## clear storage pool errors res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='clear', target=target, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'cleared')
[ "def", "clear", "(", "zpool", ",", "device", "=", "None", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "target", "=", "[", "]", "# NOTE: append the pool name and specifications", "target", ".", "append", "(", "zpool", ")", "target", ".", "append...
Clears device errors in a pool. .. warning:: The device must not be part of an active pool configuration. zpool : string name of storage pool device : string (optional) specific device to clear .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt '*' zpool.clear mypool salt '*' zpool.clear mypool /path/to/dev
[ "Clears", "device", "errors", "in", "a", "pool", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1470-L1510
train
saltstack/salt
salt/modules/zpool.py
reguid
def reguid(zpool): ''' Generates a new unique identifier for the pool .. warning:: You must ensure that all devices in this pool are online and healthy before performing this action. zpool : string name of storage pool .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.reguid myzpool ''' ## generate new GUID for pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='reguid', target=zpool, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'reguided')
python
def reguid(zpool): ''' Generates a new unique identifier for the pool .. warning:: You must ensure that all devices in this pool are online and healthy before performing this action. zpool : string name of storage pool .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.reguid myzpool ''' ## generate new GUID for pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='reguid', target=zpool, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'reguided')
[ "def", "reguid", "(", "zpool", ")", ":", "## generate new GUID for pool", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zpool_command'", "]", "(", "command", "=", "'reguid'", ",", "target", "=", "zpool", ",", ")", ",", "pyth...
Generates a new unique identifier for the pool .. warning:: You must ensure that all devices in this pool are online and healthy before performing this action. zpool : string name of storage pool .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.reguid myzpool
[ "Generates", "a", "new", "unique", "identifier", "for", "the", "pool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1513-L1541
train
saltstack/salt
salt/modules/zpool.py
upgrade
def upgrade(zpool=None, version=None): ''' .. versionadded:: 2016.3.0 Enables all supported features on the given pool zpool : string Optional storage pool, applies to all otherwize version : int Version to upgrade to, if unspecified upgrade to the highest possible .. warning:: Once this is done, the pool will no longer be accessible on systems that do not support feature flags. See zpool-features(5) for details on compatibility with systems that support feature flags, but do not support all features enabled on the pool. CLI Example: .. code-block:: bash salt '*' zpool.upgrade myzpool ''' ## Configure pool # NOTE: initialize the defaults flags = [] opts = {} # NOTE: set extra config if version: opts['-V'] = version if not zpool: flags.append('-a') ## Upgrade pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='upgrade', flags=flags, opts=opts, target=zpool, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'upgraded')
python
def upgrade(zpool=None, version=None): ''' .. versionadded:: 2016.3.0 Enables all supported features on the given pool zpool : string Optional storage pool, applies to all otherwize version : int Version to upgrade to, if unspecified upgrade to the highest possible .. warning:: Once this is done, the pool will no longer be accessible on systems that do not support feature flags. See zpool-features(5) for details on compatibility with systems that support feature flags, but do not support all features enabled on the pool. CLI Example: .. code-block:: bash salt '*' zpool.upgrade myzpool ''' ## Configure pool # NOTE: initialize the defaults flags = [] opts = {} # NOTE: set extra config if version: opts['-V'] = version if not zpool: flags.append('-a') ## Upgrade pool res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='upgrade', flags=flags, opts=opts, target=zpool, ), python_shell=False, ) return __utils__['zfs.parse_command_result'](res, 'upgraded')
[ "def", "upgrade", "(", "zpool", "=", "None", ",", "version", "=", "None", ")", ":", "## Configure pool", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "opts", "=", "{", "}", "# NOTE: set extra config", "if", "version", ":", "opts", "[", "'-V'", ...
.. versionadded:: 2016.3.0 Enables all supported features on the given pool zpool : string Optional storage pool, applies to all otherwize version : int Version to upgrade to, if unspecified upgrade to the highest possible .. warning:: Once this is done, the pool will no longer be accessible on systems that do not support feature flags. See zpool-features(5) for details on compatibility with systems that support feature flags, but do not support all features enabled on the pool. CLI Example: .. code-block:: bash salt '*' zpool.upgrade myzpool
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1572-L1618
train
saltstack/salt
salt/modules/zpool.py
history
def history(zpool=None, internal=False, verbose=False): ''' .. versionadded:: 2016.3.0 Displays the command history of the specified pools, or all pools if no pool is specified zpool : string Optional storage pool internal : boolean Toggle display of internally logged ZFS events verbose : boolean Toggle display of the user name, the hostname, and the zone in which the operation was performed CLI Example: .. code-block:: bash salt '*' zpool.upgrade myzpool ''' ret = OrderedDict() ## Configure pool # NOTE: initialize the defaults flags = [] # NOTE: set extra config if verbose: flags.append('-l') if internal: flags.append('-i') ## Lookup history res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='history', flags=flags, target=zpool, ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) else: pool = 'unknown' for line in res['stdout'].splitlines(): if line.startswith('History for'): pool = line[13:-2] ret[pool] = OrderedDict() else: if line == '': continue log_timestamp = line[0:19] log_command = line[20:] ret[pool][log_timestamp] = log_command return ret
python
def history(zpool=None, internal=False, verbose=False): ''' .. versionadded:: 2016.3.0 Displays the command history of the specified pools, or all pools if no pool is specified zpool : string Optional storage pool internal : boolean Toggle display of internally logged ZFS events verbose : boolean Toggle display of the user name, the hostname, and the zone in which the operation was performed CLI Example: .. code-block:: bash salt '*' zpool.upgrade myzpool ''' ret = OrderedDict() ## Configure pool # NOTE: initialize the defaults flags = [] # NOTE: set extra config if verbose: flags.append('-l') if internal: flags.append('-i') ## Lookup history res = __salt__['cmd.run_all']( __utils__['zfs.zpool_command']( command='history', flags=flags, target=zpool, ), python_shell=False, ) if res['retcode'] != 0: return __utils__['zfs.parse_command_result'](res) else: pool = 'unknown' for line in res['stdout'].splitlines(): if line.startswith('History for'): pool = line[13:-2] ret[pool] = OrderedDict() else: if line == '': continue log_timestamp = line[0:19] log_command = line[20:] ret[pool][log_timestamp] = log_command return ret
[ "def", "history", "(", "zpool", "=", "None", ",", "internal", "=", "False", ",", "verbose", "=", "False", ")", ":", "ret", "=", "OrderedDict", "(", ")", "## Configure pool", "# NOTE: initialize the defaults", "flags", "=", "[", "]", "# NOTE: set extra config", ...
.. versionadded:: 2016.3.0 Displays the command history of the specified pools, or all pools if no pool is specified zpool : string Optional storage pool internal : boolean Toggle display of internally logged ZFS events verbose : boolean Toggle display of the user name, the hostname, and the zone in which the operation was performed CLI Example: .. code-block:: bash salt '*' zpool.upgrade myzpool
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L1621-L1682
train
saltstack/salt
salt/states/mongodb_user.py
present
def present(name, passwd, database="admin", user=None, password=None, host="localhost", port=27017, authdb=None, roles=None): ''' Ensure that the user is present with the specified properties name The name of the user to manage passwd The password of the user to manage user MongoDB user with sufficient privilege to create the user password Password for the admin user specified with the ``user`` parameter host The hostname/IP address of the MongoDB server port The port on which MongoDB is listening database The database in which to create the user .. note:: If the database doesn't exist, it will be created. authdb The database in which to authenticate roles The roles assigned to user specified with the ``name`` parameter Example: .. code-block:: yaml mongouser-myapp: mongodb_user.present: - name: myapp - passwd: password-of-myapp - database: admin # Connect as admin:sekrit - user: admin - password: sekrit - roles: - readWrite - userAdmin - dbOwner ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'User {0} is already present'.format(name)} # setup default empty roles if not provided to preserve previous API interface if roles is None: roles = [] # Check for valid port try: port = int(port) except TypeError: ret['result'] = False ret['comment'] = 'Port ({0}) is not an integer.'.format(port) return ret # check if user exists users = __salt__['mongodb.user_find'](name, user, password, host, port, database, authdb) if users: # check for errors returned in users e.g. # users= (False, 'Failed to connect to MongoDB database localhost:27017') # users= (False, 'not authorized on admin to execute command { usersInfo: "root" }') if not users[0]: ret['result'] = False ret['comment'] = "Mongo Err: {0}".format(users[1]) return ret # check each user occurrence for usr in users: # prepare empty list for current roles current_roles = [] # iterate over user roles and append each to current_roles list for role in usr['roles']: # check correct database to be sure to fill current_roles only for desired db if role['db'] == database: current_roles.append(role['role']) # fill changes if the roles and current roles differ if not set(current_roles) == set(roles): ret['changes'].update({name: {'database': database, 'roles': {'old': current_roles, 'new': roles}}}) __salt__['mongodb.user_create'](name, passwd, user, password, host, port, database=database, authdb=authdb, roles=roles) return ret # if the check does not return a boolean, return an error # this may be the case if there is a database connection error if not isinstance(users, list): ret['comment'] = users ret['result'] = False return ret if __opts__['test']: ret['result'] = None ret['comment'] = ('User {0} is not present and needs to be created' ).format(name) return ret # The user is not present, make it! if __salt__['mongodb.user_create'](name, passwd, user, password, host, port, database=database, authdb=authdb, roles=roles): ret['comment'] = 'User {0} has been created'.format(name) ret['changes'][name] = 'Present' else: ret['comment'] = 'Failed to create database {0}'.format(name) ret['result'] = False return ret
python
def present(name, passwd, database="admin", user=None, password=None, host="localhost", port=27017, authdb=None, roles=None): ''' Ensure that the user is present with the specified properties name The name of the user to manage passwd The password of the user to manage user MongoDB user with sufficient privilege to create the user password Password for the admin user specified with the ``user`` parameter host The hostname/IP address of the MongoDB server port The port on which MongoDB is listening database The database in which to create the user .. note:: If the database doesn't exist, it will be created. authdb The database in which to authenticate roles The roles assigned to user specified with the ``name`` parameter Example: .. code-block:: yaml mongouser-myapp: mongodb_user.present: - name: myapp - passwd: password-of-myapp - database: admin # Connect as admin:sekrit - user: admin - password: sekrit - roles: - readWrite - userAdmin - dbOwner ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'User {0} is already present'.format(name)} # setup default empty roles if not provided to preserve previous API interface if roles is None: roles = [] # Check for valid port try: port = int(port) except TypeError: ret['result'] = False ret['comment'] = 'Port ({0}) is not an integer.'.format(port) return ret # check if user exists users = __salt__['mongodb.user_find'](name, user, password, host, port, database, authdb) if users: # check for errors returned in users e.g. # users= (False, 'Failed to connect to MongoDB database localhost:27017') # users= (False, 'not authorized on admin to execute command { usersInfo: "root" }') if not users[0]: ret['result'] = False ret['comment'] = "Mongo Err: {0}".format(users[1]) return ret # check each user occurrence for usr in users: # prepare empty list for current roles current_roles = [] # iterate over user roles and append each to current_roles list for role in usr['roles']: # check correct database to be sure to fill current_roles only for desired db if role['db'] == database: current_roles.append(role['role']) # fill changes if the roles and current roles differ if not set(current_roles) == set(roles): ret['changes'].update({name: {'database': database, 'roles': {'old': current_roles, 'new': roles}}}) __salt__['mongodb.user_create'](name, passwd, user, password, host, port, database=database, authdb=authdb, roles=roles) return ret # if the check does not return a boolean, return an error # this may be the case if there is a database connection error if not isinstance(users, list): ret['comment'] = users ret['result'] = False return ret if __opts__['test']: ret['result'] = None ret['comment'] = ('User {0} is not present and needs to be created' ).format(name) return ret # The user is not present, make it! if __salt__['mongodb.user_create'](name, passwd, user, password, host, port, database=database, authdb=authdb, roles=roles): ret['comment'] = 'User {0} has been created'.format(name) ret['changes'][name] = 'Present' else: ret['comment'] = 'Failed to create database {0}'.format(name) ret['result'] = False return ret
[ "def", "present", "(", "name", ",", "passwd", ",", "database", "=", "\"admin\"", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "\"localhost\"", ",", "port", "=", "27017", ",", "authdb", "=", "None", ",", "roles", "=", "Non...
Ensure that the user is present with the specified properties name The name of the user to manage passwd The password of the user to manage user MongoDB user with sufficient privilege to create the user password Password for the admin user specified with the ``user`` parameter host The hostname/IP address of the MongoDB server port The port on which MongoDB is listening database The database in which to create the user .. note:: If the database doesn't exist, it will be created. authdb The database in which to authenticate roles The roles assigned to user specified with the ``name`` parameter Example: .. code-block:: yaml mongouser-myapp: mongodb_user.present: - name: myapp - passwd: password-of-myapp - database: admin # Connect as admin:sekrit - user: admin - password: sekrit - roles: - readWrite - userAdmin - dbOwner
[ "Ensure", "that", "the", "user", "is", "present", "with", "the", "specified", "properties" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mongodb_user.py#L20-L145
train
saltstack/salt
salt/states/mongodb_user.py
absent
def absent(name, user=None, password=None, host=None, port=None, database="admin", authdb=None): ''' Ensure that the named user is absent name The name of the user to remove user MongoDB user with sufficient privilege to create the user password Password for the admin user specified by the ``user`` parameter host The hostname/IP address of the MongoDB server port The port on which MongoDB is listening database The database from which to remove the user specified by the ``name`` parameter authdb The database in which to authenticate ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if user exists and remove it user_exists = __salt__['mongodb.user_exists'](name, user, password, host, port, database=database, authdb=authdb) if user_exists is True: if __opts__['test']: ret['result'] = None ret['comment'] = ('User {0} is present and needs to be removed' ).format(name) return ret if __salt__['mongodb.user_remove'](name, user, password, host, port, database=database, authdb=authdb): ret['comment'] = 'User {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret # if the check does not return a boolean, return an error # this may be the case if there is a database connection error if not isinstance(user_exists, bool): ret['comment'] = user_exists ret['result'] = False return ret # fallback ret['comment'] = 'User {0} is not present'.format(name) return ret
python
def absent(name, user=None, password=None, host=None, port=None, database="admin", authdb=None): ''' Ensure that the named user is absent name The name of the user to remove user MongoDB user with sufficient privilege to create the user password Password for the admin user specified by the ``user`` parameter host The hostname/IP address of the MongoDB server port The port on which MongoDB is listening database The database from which to remove the user specified by the ``name`` parameter authdb The database in which to authenticate ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if user exists and remove it user_exists = __salt__['mongodb.user_exists'](name, user, password, host, port, database=database, authdb=authdb) if user_exists is True: if __opts__['test']: ret['result'] = None ret['comment'] = ('User {0} is present and needs to be removed' ).format(name) return ret if __salt__['mongodb.user_remove'](name, user, password, host, port, database=database, authdb=authdb): ret['comment'] = 'User {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret # if the check does not return a boolean, return an error # this may be the case if there is a database connection error if not isinstance(user_exists, bool): ret['comment'] = user_exists ret['result'] = False return ret # fallback ret['comment'] = 'User {0} is not present'.format(name) return ret
[ "def", "absent", "(", "name", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "\"admin\"", ",", "authdb", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "na...
Ensure that the named user is absent name The name of the user to remove user MongoDB user with sufficient privilege to create the user password Password for the admin user specified by the ``user`` parameter host The hostname/IP address of the MongoDB server port The port on which MongoDB is listening database The database from which to remove the user specified by the ``name`` parameter authdb The database in which to authenticate
[ "Ensure", "that", "the", "named", "user", "is", "absent" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mongodb_user.py#L148-L207
train
saltstack/salt
salt/modules/boto_asg.py
exists
def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an autoscale group exists. CLI example:: salt myminion boto_asg.exists myasg region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: _conn = conn.get_all_groups(names=[name]) if _conn: return True else: msg = 'The autoscale group does not exist in region {0}'.format(region) log.debug(msg) return False except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return False
python
def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an autoscale group exists. CLI example:: salt myminion boto_asg.exists myasg region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: _conn = conn.get_all_groups(names=[name]) if _conn: return True else: msg = 'The autoscale group does not exist in region {0}'.format(region) log.debug(msg) return False except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return False
[ "def", "exists", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "="...
Check to see if an autoscale group exists. CLI example:: salt myminion boto_asg.exists myasg region=us-east-1
[ "Check", "to", "see", "if", "an", "autoscale", "group", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L103-L129
train
saltstack/salt
salt/modules/boto_asg.py
get_config
def get_config(name, region=None, key=None, keyid=None, profile=None): ''' Get the configuration for an autoscale group. CLI example:: salt myminion boto_asg.get_config myasg region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: asg = conn.get_all_groups(names=[name]) if asg: asg = asg[0] else: return {} ret = odict.OrderedDict() attrs = ['name', 'availability_zones', 'default_cooldown', 'desired_capacity', 'health_check_period', 'health_check_type', 'launch_config_name', 'load_balancers', 'max_size', 'min_size', 'placement_group', 'vpc_zone_identifier', 'tags', 'termination_policies', 'suspended_processes'] for attr in attrs: # Tags are objects, so we need to turn them into dicts. if attr == 'tags': _tags = [] for tag in asg.tags: _tag = odict.OrderedDict() _tag['key'] = tag.key _tag['value'] = tag.value _tag['propagate_at_launch'] = tag.propagate_at_launch _tags.append(_tag) ret['tags'] = _tags # Boto accepts a string or list as input for vpc_zone_identifier, # but always returns a comma separated list. We require lists in # states. elif attr == 'vpc_zone_identifier': ret[attr] = getattr(asg, attr).split(',') # convert SuspendedProcess objects to names elif attr == 'suspended_processes': suspended_processes = getattr(asg, attr) ret[attr] = sorted([x.process_name for x in suspended_processes]) else: ret[attr] = getattr(asg, attr) # scaling policies policies = conn.get_all_policies(as_group=name) ret["scaling_policies"] = [] for policy in policies: ret["scaling_policies"].append( dict([ ("name", policy.name), ("adjustment_type", policy.adjustment_type), ("scaling_adjustment", policy.scaling_adjustment), ("min_adjustment_step", policy.min_adjustment_step), ("cooldown", policy.cooldown) ]) ) # scheduled actions actions = conn.get_all_scheduled_actions(as_group=name) ret['scheduled_actions'] = {} for action in actions: end_time = None if action.end_time: end_time = action.end_time.isoformat() ret['scheduled_actions'][action.name] = dict([ ("min_size", action.min_size), ("max_size", action.max_size), # AWS bug ("desired_capacity", int(action.desired_capacity)), ("start_time", action.start_time.isoformat()), ("end_time", end_time), ("recurrence", action.recurrence) ]) return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return {}
python
def get_config(name, region=None, key=None, keyid=None, profile=None): ''' Get the configuration for an autoscale group. CLI example:: salt myminion boto_asg.get_config myasg region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: asg = conn.get_all_groups(names=[name]) if asg: asg = asg[0] else: return {} ret = odict.OrderedDict() attrs = ['name', 'availability_zones', 'default_cooldown', 'desired_capacity', 'health_check_period', 'health_check_type', 'launch_config_name', 'load_balancers', 'max_size', 'min_size', 'placement_group', 'vpc_zone_identifier', 'tags', 'termination_policies', 'suspended_processes'] for attr in attrs: # Tags are objects, so we need to turn them into dicts. if attr == 'tags': _tags = [] for tag in asg.tags: _tag = odict.OrderedDict() _tag['key'] = tag.key _tag['value'] = tag.value _tag['propagate_at_launch'] = tag.propagate_at_launch _tags.append(_tag) ret['tags'] = _tags # Boto accepts a string or list as input for vpc_zone_identifier, # but always returns a comma separated list. We require lists in # states. elif attr == 'vpc_zone_identifier': ret[attr] = getattr(asg, attr).split(',') # convert SuspendedProcess objects to names elif attr == 'suspended_processes': suspended_processes = getattr(asg, attr) ret[attr] = sorted([x.process_name for x in suspended_processes]) else: ret[attr] = getattr(asg, attr) # scaling policies policies = conn.get_all_policies(as_group=name) ret["scaling_policies"] = [] for policy in policies: ret["scaling_policies"].append( dict([ ("name", policy.name), ("adjustment_type", policy.adjustment_type), ("scaling_adjustment", policy.scaling_adjustment), ("min_adjustment_step", policy.min_adjustment_step), ("cooldown", policy.cooldown) ]) ) # scheduled actions actions = conn.get_all_scheduled_actions(as_group=name) ret['scheduled_actions'] = {} for action in actions: end_time = None if action.end_time: end_time = action.end_time.isoformat() ret['scheduled_actions'][action.name] = dict([ ("min_size", action.min_size), ("max_size", action.max_size), # AWS bug ("desired_capacity", int(action.desired_capacity)), ("start_time", action.start_time.isoformat()), ("end_time", end_time), ("recurrence", action.recurrence) ]) return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return {}
[ "def", "get_config", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", ...
Get the configuration for an autoscale group. CLI example:: salt myminion boto_asg.get_config myasg region=us-east-1
[ "Get", "the", "configuration", "for", "an", "autoscale", "group", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L132-L215
train
saltstack/salt
salt/modules/boto_asg.py
create
def create(name, launch_config_name, availability_zones, min_size, max_size, desired_capacity=None, load_balancers=None, default_cooldown=None, health_check_type=None, health_check_period=None, placement_group=None, vpc_zone_identifier=None, tags=None, termination_policies=None, suspended_processes=None, scaling_policies=None, scheduled_actions=None, region=None, notification_arn=None, notification_types=None, key=None, keyid=None, profile=None): ''' Create an autoscale group. CLI example:: salt myminion boto_asg.create myasg mylc '["us-east-1a", "us-east-1e"]' 1 10 load_balancers='["myelb", "myelb2"]' tags='[{"key": "Name", value="myasg", "propagate_at_launch": True}]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(load_balancers, six.string_types): load_balancers = salt.utils.json.loads(load_balancers) if isinstance(vpc_zone_identifier, six.string_types): vpc_zone_identifier = salt.utils.json.loads(vpc_zone_identifier) if isinstance(tags, six.string_types): tags = salt.utils.json.loads(tags) # Make a list of tag objects from the dict. _tags = [] if tags: for tag in tags: try: key = tag.get('key') except KeyError: log.error('Tag missing key.') return False try: value = tag.get('value') except KeyError: log.error('Tag missing value.') return False propagate_at_launch = tag.get('propagate_at_launch', False) _tag = autoscale.Tag(key=key, value=value, resource_id=name, propagate_at_launch=propagate_at_launch) _tags.append(_tag) if isinstance(termination_policies, six.string_types): termination_policies = salt.utils.json.loads(termination_policies) if isinstance(suspended_processes, six.string_types): suspended_processes = salt.utils.json.loads(suspended_processes) if isinstance(scheduled_actions, six.string_types): scheduled_actions = salt.utils.json.loads(scheduled_actions) retries = 30 while True: try: _asg = autoscale.AutoScalingGroup( name=name, launch_config=launch_config_name, availability_zones=availability_zones, min_size=min_size, max_size=max_size, desired_capacity=desired_capacity, load_balancers=load_balancers, default_cooldown=default_cooldown, health_check_type=health_check_type, health_check_period=health_check_period, placement_group=placement_group, tags=_tags, vpc_zone_identifier=vpc_zone_identifier, termination_policies=termination_policies, suspended_processes=suspended_processes) conn.create_auto_scaling_group(_asg) # create scaling policies _create_scaling_policies(conn, name, scaling_policies) # create scheduled actions _create_scheduled_actions(conn, name, scheduled_actions) # create notifications if notification_arn and notification_types: conn.put_notification_configuration(_asg, notification_arn, notification_types) log.info('Created ASG %s', name) return True except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) msg = 'Failed to create ASG %s', name log.error(msg) return False
python
def create(name, launch_config_name, availability_zones, min_size, max_size, desired_capacity=None, load_balancers=None, default_cooldown=None, health_check_type=None, health_check_period=None, placement_group=None, vpc_zone_identifier=None, tags=None, termination_policies=None, suspended_processes=None, scaling_policies=None, scheduled_actions=None, region=None, notification_arn=None, notification_types=None, key=None, keyid=None, profile=None): ''' Create an autoscale group. CLI example:: salt myminion boto_asg.create myasg mylc '["us-east-1a", "us-east-1e"]' 1 10 load_balancers='["myelb", "myelb2"]' tags='[{"key": "Name", value="myasg", "propagate_at_launch": True}]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(load_balancers, six.string_types): load_balancers = salt.utils.json.loads(load_balancers) if isinstance(vpc_zone_identifier, six.string_types): vpc_zone_identifier = salt.utils.json.loads(vpc_zone_identifier) if isinstance(tags, six.string_types): tags = salt.utils.json.loads(tags) # Make a list of tag objects from the dict. _tags = [] if tags: for tag in tags: try: key = tag.get('key') except KeyError: log.error('Tag missing key.') return False try: value = tag.get('value') except KeyError: log.error('Tag missing value.') return False propagate_at_launch = tag.get('propagate_at_launch', False) _tag = autoscale.Tag(key=key, value=value, resource_id=name, propagate_at_launch=propagate_at_launch) _tags.append(_tag) if isinstance(termination_policies, six.string_types): termination_policies = salt.utils.json.loads(termination_policies) if isinstance(suspended_processes, six.string_types): suspended_processes = salt.utils.json.loads(suspended_processes) if isinstance(scheduled_actions, six.string_types): scheduled_actions = salt.utils.json.loads(scheduled_actions) retries = 30 while True: try: _asg = autoscale.AutoScalingGroup( name=name, launch_config=launch_config_name, availability_zones=availability_zones, min_size=min_size, max_size=max_size, desired_capacity=desired_capacity, load_balancers=load_balancers, default_cooldown=default_cooldown, health_check_type=health_check_type, health_check_period=health_check_period, placement_group=placement_group, tags=_tags, vpc_zone_identifier=vpc_zone_identifier, termination_policies=termination_policies, suspended_processes=suspended_processes) conn.create_auto_scaling_group(_asg) # create scaling policies _create_scaling_policies(conn, name, scaling_policies) # create scheduled actions _create_scheduled_actions(conn, name, scheduled_actions) # create notifications if notification_arn and notification_types: conn.put_notification_configuration(_asg, notification_arn, notification_types) log.info('Created ASG %s', name) return True except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) msg = 'Failed to create ASG %s', name log.error(msg) return False
[ "def", "create", "(", "name", ",", "launch_config_name", ",", "availability_zones", ",", "min_size", ",", "max_size", ",", "desired_capacity", "=", "None", ",", "load_balancers", "=", "None", ",", "default_cooldown", "=", "None", ",", "health_check_type", "=", "...
Create an autoscale group. CLI example:: salt myminion boto_asg.create myasg mylc '["us-east-1a", "us-east-1e"]' 1 10 load_balancers='["myelb", "myelb2"]' tags='[{"key": "Name", value="myasg", "propagate_at_launch": True}]'
[ "Create", "an", "autoscale", "group", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L218-L300
train
saltstack/salt
salt/modules/boto_asg.py
update
def update(name, launch_config_name, availability_zones, min_size, max_size, desired_capacity=None, load_balancers=None, default_cooldown=None, health_check_type=None, health_check_period=None, placement_group=None, vpc_zone_identifier=None, tags=None, termination_policies=None, suspended_processes=None, scaling_policies=None, scheduled_actions=None, notification_arn=None, notification_types=None, region=None, key=None, keyid=None, profile=None): ''' Update an autoscale group. CLI example:: salt myminion boto_asg.update myasg mylc '["us-east-1a", "us-east-1e"]' 1 10 load_balancers='["myelb", "myelb2"]' tags='[{"key": "Name", value="myasg", "propagate_at_launch": True}]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn3 = _get_conn_autoscaling_boto3(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False, "failed to connect to AWS" if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(load_balancers, six.string_types): load_balancers = salt.utils.json.loads(load_balancers) if isinstance(vpc_zone_identifier, six.string_types): vpc_zone_identifier = salt.utils.json.loads(vpc_zone_identifier) if isinstance(tags, six.string_types): tags = salt.utils.json.loads(tags) if isinstance(termination_policies, six.string_types): termination_policies = salt.utils.json.loads(termination_policies) if isinstance(suspended_processes, six.string_types): suspended_processes = salt.utils.json.loads(suspended_processes) if isinstance(scheduled_actions, six.string_types): scheduled_actions = salt.utils.json.loads(scheduled_actions) # Massage our tagset into add / remove lists # Use a boto3 call here b/c the boto2 call doeesn't implement filters current_tags = conn3.describe_tags(Filters=[{'Name': 'auto-scaling-group', 'Values': [name]}]).get('Tags', []) current_tags = [{'key': t['Key'], 'value': t['Value'], 'resource_id': t['ResourceId'], 'propagate_at_launch': t.get('PropagateAtLaunch', False)} for t in current_tags] add_tags = [] desired_tags = [] if tags: tags = __utils__['boto3.ordered'](tags) for tag in tags: try: key = tag.get('key') except KeyError: log.error('Tag missing key.') return False, "Tag {0} missing key".format(tag) try: value = tag.get('value') except KeyError: log.error('Tag missing value.') return False, "Tag {0} missing value".format(tag) propagate_at_launch = tag.get('propagate_at_launch', False) _tag = {'key': key, 'value': value, 'resource_id': name, 'propagate_at_launch': propagate_at_launch} if _tag not in current_tags: add_tags.append(_tag) desired_tags.append(_tag) delete_tags = [t for t in current_tags if t not in desired_tags] retries = 30 while True: try: _asg = autoscale.AutoScalingGroup( connection=conn, name=name, launch_config=launch_config_name, availability_zones=availability_zones, min_size=min_size, max_size=max_size, desired_capacity=desired_capacity, load_balancers=load_balancers, default_cooldown=default_cooldown, health_check_type=health_check_type, health_check_period=health_check_period, placement_group=placement_group, tags=add_tags, vpc_zone_identifier=vpc_zone_identifier, termination_policies=termination_policies) if notification_arn and notification_types: conn.put_notification_configuration(_asg, notification_arn, notification_types) _asg.update() # Seems the update call doesn't handle tags, so we'll need to update # that separately. if add_tags: log.debug('Adding/updating tags from ASG: %s', add_tags) conn.create_or_update_tags([autoscale.Tag(**t) for t in add_tags]) if delete_tags: log.debug('Deleting tags from ASG: %s', delete_tags) conn.delete_tags([autoscale.Tag(**t) for t in delete_tags]) # update doesn't handle suspended_processes either # Resume all processes _asg.resume_processes() # suspend any that are specified. Note that the boto default of empty # list suspends all; don't do that. if suspended_processes: _asg.suspend_processes(suspended_processes) log.info('Updated ASG %s', name) # ### scaling policies # delete all policies, then recreate them for policy in conn.get_all_policies(as_group=name): conn.delete_policy(policy.name, autoscale_group=name) _create_scaling_policies(conn, name, scaling_policies) # ### scheduled actions # delete all scheduled actions, then recreate them for scheduled_action in conn.get_all_scheduled_actions(as_group=name): conn.delete_scheduled_action( scheduled_action.name, autoscale_group=name ) _create_scheduled_actions(conn, name, scheduled_actions) return True, '' except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) msg = 'Failed to update ASG {0}'.format(name) log.error(msg) return False, six.text_type(e)
python
def update(name, launch_config_name, availability_zones, min_size, max_size, desired_capacity=None, load_balancers=None, default_cooldown=None, health_check_type=None, health_check_period=None, placement_group=None, vpc_zone_identifier=None, tags=None, termination_policies=None, suspended_processes=None, scaling_policies=None, scheduled_actions=None, notification_arn=None, notification_types=None, region=None, key=None, keyid=None, profile=None): ''' Update an autoscale group. CLI example:: salt myminion boto_asg.update myasg mylc '["us-east-1a", "us-east-1e"]' 1 10 load_balancers='["myelb", "myelb2"]' tags='[{"key": "Name", value="myasg", "propagate_at_launch": True}]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn3 = _get_conn_autoscaling_boto3(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False, "failed to connect to AWS" if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(load_balancers, six.string_types): load_balancers = salt.utils.json.loads(load_balancers) if isinstance(vpc_zone_identifier, six.string_types): vpc_zone_identifier = salt.utils.json.loads(vpc_zone_identifier) if isinstance(tags, six.string_types): tags = salt.utils.json.loads(tags) if isinstance(termination_policies, six.string_types): termination_policies = salt.utils.json.loads(termination_policies) if isinstance(suspended_processes, six.string_types): suspended_processes = salt.utils.json.loads(suspended_processes) if isinstance(scheduled_actions, six.string_types): scheduled_actions = salt.utils.json.loads(scheduled_actions) # Massage our tagset into add / remove lists # Use a boto3 call here b/c the boto2 call doeesn't implement filters current_tags = conn3.describe_tags(Filters=[{'Name': 'auto-scaling-group', 'Values': [name]}]).get('Tags', []) current_tags = [{'key': t['Key'], 'value': t['Value'], 'resource_id': t['ResourceId'], 'propagate_at_launch': t.get('PropagateAtLaunch', False)} for t in current_tags] add_tags = [] desired_tags = [] if tags: tags = __utils__['boto3.ordered'](tags) for tag in tags: try: key = tag.get('key') except KeyError: log.error('Tag missing key.') return False, "Tag {0} missing key".format(tag) try: value = tag.get('value') except KeyError: log.error('Tag missing value.') return False, "Tag {0} missing value".format(tag) propagate_at_launch = tag.get('propagate_at_launch', False) _tag = {'key': key, 'value': value, 'resource_id': name, 'propagate_at_launch': propagate_at_launch} if _tag not in current_tags: add_tags.append(_tag) desired_tags.append(_tag) delete_tags = [t for t in current_tags if t not in desired_tags] retries = 30 while True: try: _asg = autoscale.AutoScalingGroup( connection=conn, name=name, launch_config=launch_config_name, availability_zones=availability_zones, min_size=min_size, max_size=max_size, desired_capacity=desired_capacity, load_balancers=load_balancers, default_cooldown=default_cooldown, health_check_type=health_check_type, health_check_period=health_check_period, placement_group=placement_group, tags=add_tags, vpc_zone_identifier=vpc_zone_identifier, termination_policies=termination_policies) if notification_arn and notification_types: conn.put_notification_configuration(_asg, notification_arn, notification_types) _asg.update() # Seems the update call doesn't handle tags, so we'll need to update # that separately. if add_tags: log.debug('Adding/updating tags from ASG: %s', add_tags) conn.create_or_update_tags([autoscale.Tag(**t) for t in add_tags]) if delete_tags: log.debug('Deleting tags from ASG: %s', delete_tags) conn.delete_tags([autoscale.Tag(**t) for t in delete_tags]) # update doesn't handle suspended_processes either # Resume all processes _asg.resume_processes() # suspend any that are specified. Note that the boto default of empty # list suspends all; don't do that. if suspended_processes: _asg.suspend_processes(suspended_processes) log.info('Updated ASG %s', name) # ### scaling policies # delete all policies, then recreate them for policy in conn.get_all_policies(as_group=name): conn.delete_policy(policy.name, autoscale_group=name) _create_scaling_policies(conn, name, scaling_policies) # ### scheduled actions # delete all scheduled actions, then recreate them for scheduled_action in conn.get_all_scheduled_actions(as_group=name): conn.delete_scheduled_action( scheduled_action.name, autoscale_group=name ) _create_scheduled_actions(conn, name, scheduled_actions) return True, '' except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) msg = 'Failed to update ASG {0}'.format(name) log.error(msg) return False, six.text_type(e)
[ "def", "update", "(", "name", ",", "launch_config_name", ",", "availability_zones", ",", "min_size", ",", "max_size", ",", "desired_capacity", "=", "None", ",", "load_balancers", "=", "None", ",", "default_cooldown", "=", "None", ",", "health_check_type", "=", "...
Update an autoscale group. CLI example:: salt myminion boto_asg.update myasg mylc '["us-east-1a", "us-east-1e"]' 1 10 load_balancers='["myelb", "myelb2"]' tags='[{"key": "Name", value="myasg", "propagate_at_launch": True}]'
[ "Update", "an", "autoscale", "group", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L303-L429
train
saltstack/salt
salt/modules/boto_asg.py
_create_scaling_policies
def _create_scaling_policies(conn, as_name, scaling_policies): 'helper function to create scaling policies' if scaling_policies: for policy in scaling_policies: policy = autoscale.policy.ScalingPolicy( name=policy["name"], as_name=as_name, adjustment_type=policy["adjustment_type"], scaling_adjustment=policy["scaling_adjustment"], min_adjustment_step=policy.get("min_adjustment_step", None), cooldown=policy["cooldown"]) conn.create_scaling_policy(policy)
python
def _create_scaling_policies(conn, as_name, scaling_policies): 'helper function to create scaling policies' if scaling_policies: for policy in scaling_policies: policy = autoscale.policy.ScalingPolicy( name=policy["name"], as_name=as_name, adjustment_type=policy["adjustment_type"], scaling_adjustment=policy["scaling_adjustment"], min_adjustment_step=policy.get("min_adjustment_step", None), cooldown=policy["cooldown"]) conn.create_scaling_policy(policy)
[ "def", "_create_scaling_policies", "(", "conn", ",", "as_name", ",", "scaling_policies", ")", ":", "if", "scaling_policies", ":", "for", "policy", "in", "scaling_policies", ":", "policy", "=", "autoscale", ".", "policy", ".", "ScalingPolicy", "(", "name", "=", ...
helper function to create scaling policies
[ "helper", "function", "to", "create", "scaling", "policies" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L432-L443
train
saltstack/salt
salt/modules/boto_asg.py
_create_scheduled_actions
def _create_scheduled_actions(conn, as_name, scheduled_actions): ''' Helper function to create scheduled actions ''' if scheduled_actions: for name, action in six.iteritems(scheduled_actions): if 'start_time' in action and isinstance(action['start_time'], six.string_types): action['start_time'] = datetime.datetime.strptime( action['start_time'], DATE_FORMAT ) if 'end_time' in action and isinstance(action['end_time'], six.string_types): action['end_time'] = datetime.datetime.strptime( action['end_time'], DATE_FORMAT ) conn.create_scheduled_group_action(as_name, name, desired_capacity=action.get('desired_capacity'), min_size=action.get('min_size'), max_size=action.get('max_size'), start_time=action.get('start_time'), end_time=action.get('end_time'), recurrence=action.get('recurrence') )
python
def _create_scheduled_actions(conn, as_name, scheduled_actions): ''' Helper function to create scheduled actions ''' if scheduled_actions: for name, action in six.iteritems(scheduled_actions): if 'start_time' in action and isinstance(action['start_time'], six.string_types): action['start_time'] = datetime.datetime.strptime( action['start_time'], DATE_FORMAT ) if 'end_time' in action and isinstance(action['end_time'], six.string_types): action['end_time'] = datetime.datetime.strptime( action['end_time'], DATE_FORMAT ) conn.create_scheduled_group_action(as_name, name, desired_capacity=action.get('desired_capacity'), min_size=action.get('min_size'), max_size=action.get('max_size'), start_time=action.get('start_time'), end_time=action.get('end_time'), recurrence=action.get('recurrence') )
[ "def", "_create_scheduled_actions", "(", "conn", ",", "as_name", ",", "scheduled_actions", ")", ":", "if", "scheduled_actions", ":", "for", "name", ",", "action", "in", "six", ".", "iteritems", "(", "scheduled_actions", ")", ":", "if", "'start_time'", "in", "a...
Helper function to create scheduled actions
[ "Helper", "function", "to", "create", "scheduled", "actions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L446-L467
train
saltstack/salt
salt/modules/boto_asg.py
get_cloud_init_mime
def get_cloud_init_mime(cloud_init): ''' Get a mime multipart encoded string from a cloud-init dict. Currently supports boothooks, scripts and cloud-config. CLI Example: .. code-block:: bash salt myminion boto.get_cloud_init_mime <cloud init> ''' if isinstance(cloud_init, six.string_types): cloud_init = salt.utils.json.loads(cloud_init) _cloud_init = email.mime.multipart.MIMEMultipart() if 'boothooks' in cloud_init: for script_name, script in six.iteritems(cloud_init['boothooks']): _script = email.mime.text.MIMEText(script, 'cloud-boothook') _cloud_init.attach(_script) if 'scripts' in cloud_init: for script_name, script in six.iteritems(cloud_init['scripts']): _script = email.mime.text.MIMEText(script, 'x-shellscript') _cloud_init.attach(_script) if 'cloud-config' in cloud_init: cloud_config = cloud_init['cloud-config'] _cloud_config = email.mime.text.MIMEText( salt.utils.yaml.safe_dump(cloud_config, default_flow_style=False), 'cloud-config') _cloud_init.attach(_cloud_config) return _cloud_init.as_string()
python
def get_cloud_init_mime(cloud_init): ''' Get a mime multipart encoded string from a cloud-init dict. Currently supports boothooks, scripts and cloud-config. CLI Example: .. code-block:: bash salt myminion boto.get_cloud_init_mime <cloud init> ''' if isinstance(cloud_init, six.string_types): cloud_init = salt.utils.json.loads(cloud_init) _cloud_init = email.mime.multipart.MIMEMultipart() if 'boothooks' in cloud_init: for script_name, script in six.iteritems(cloud_init['boothooks']): _script = email.mime.text.MIMEText(script, 'cloud-boothook') _cloud_init.attach(_script) if 'scripts' in cloud_init: for script_name, script in six.iteritems(cloud_init['scripts']): _script = email.mime.text.MIMEText(script, 'x-shellscript') _cloud_init.attach(_script) if 'cloud-config' in cloud_init: cloud_config = cloud_init['cloud-config'] _cloud_config = email.mime.text.MIMEText( salt.utils.yaml.safe_dump(cloud_config, default_flow_style=False), 'cloud-config') _cloud_init.attach(_cloud_config) return _cloud_init.as_string()
[ "def", "get_cloud_init_mime", "(", "cloud_init", ")", ":", "if", "isinstance", "(", "cloud_init", ",", "six", ".", "string_types", ")", ":", "cloud_init", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "cloud_init", ")", "_cloud_init", "=", "em...
Get a mime multipart encoded string from a cloud-init dict. Currently supports boothooks, scripts and cloud-config. CLI Example: .. code-block:: bash salt myminion boto.get_cloud_init_mime <cloud init>
[ "Get", "a", "mime", "multipart", "encoded", "string", "from", "a", "cloud", "-", "init", "dict", ".", "Currently", "supports", "boothooks", "scripts", "and", "cloud", "-", "config", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L498-L526
train
saltstack/salt
salt/modules/boto_asg.py
launch_configuration_exists
def launch_configuration_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check for a launch configuration's existence. CLI example:: salt myminion boto_asg.launch_configuration_exists mylc ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lc = conn.get_all_launch_configurations(names=[name]) if lc: return True else: msg = 'The launch configuration does not exist in region {0}'.format(region) log.debug(msg) return False except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return False
python
def launch_configuration_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check for a launch configuration's existence. CLI example:: salt myminion boto_asg.launch_configuration_exists mylc ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lc = conn.get_all_launch_configurations(names=[name]) if lc: return True else: msg = 'The launch configuration does not exist in region {0}'.format(region) log.debug(msg) return False except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return False
[ "def", "launch_configuration_exists", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ...
Check for a launch configuration's existence. CLI example:: salt myminion boto_asg.launch_configuration_exists mylc
[ "Check", "for", "a", "launch", "configuration", "s", "existence", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L529-L556
train
saltstack/salt
salt/modules/boto_asg.py
get_all_launch_configurations
def get_all_launch_configurations(region=None, key=None, keyid=None, profile=None): ''' Fetch and return all Launch Configuration with details. CLI example:: salt myminion boto_asg.get_all_launch_configurations ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: return conn.get_all_launch_configurations() except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return []
python
def get_all_launch_configurations(region=None, key=None, keyid=None, profile=None): ''' Fetch and return all Launch Configuration with details. CLI example:: salt myminion boto_asg.get_all_launch_configurations ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: return conn.get_all_launch_configurations() except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return []
[ "def", "get_all_launch_configurations", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid",...
Fetch and return all Launch Configuration with details. CLI example:: salt myminion boto_asg.get_all_launch_configurations
[ "Fetch", "and", "return", "all", "Launch", "Configuration", "with", "details", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L559-L580
train
saltstack/salt
salt/modules/boto_asg.py
list_launch_configurations
def list_launch_configurations(region=None, key=None, keyid=None, profile=None): ''' List all Launch Configurations. CLI example:: salt myminion boto_asg.list_launch_configurations ''' ret = get_all_launch_configurations(region, key, keyid, profile) return [r.name for r in ret]
python
def list_launch_configurations(region=None, key=None, keyid=None, profile=None): ''' List all Launch Configurations. CLI example:: salt myminion boto_asg.list_launch_configurations ''' ret = get_all_launch_configurations(region, key, keyid, profile) return [r.name for r in ret]
[ "def", "list_launch_configurations", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "get_all_launch_configurations", "(", "region", ",", "key", ",", "keyid", ",", "profile"...
List all Launch Configurations. CLI example:: salt myminion boto_asg.list_launch_configurations
[ "List", "all", "Launch", "Configurations", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L583-L593
train
saltstack/salt
salt/modules/boto_asg.py
create_launch_configuration
def create_launch_configuration(name, image_id, key_name=None, vpc_id=None, vpc_name=None, security_groups=None, user_data=None, instance_type='m1.small', kernel_id=None, ramdisk_id=None, block_device_mappings=None, instance_monitoring=False, spot_price=None, instance_profile_name=None, ebs_optimized=False, associate_public_ip_address=None, volume_type=None, delete_on_termination=True, iops=None, use_block_device_types=False, region=None, key=None, keyid=None, profile=None): ''' Create a launch configuration. CLI example:: salt myminion boto_asg.create_launch_configuration mylc image_id=ami-0b9c9f62 key_name='mykey' security_groups='["mygroup"]' instance_type='c3.2xlarge' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) if isinstance(block_device_mappings, six.string_types): block_device_mappings = salt.utils.json.loads(block_device_mappings) _bdms = [] if block_device_mappings: # Boto requires objects for the mappings and the devices. _block_device_map = blockdevicemapping.BlockDeviceMapping() for block_device_dict in block_device_mappings: for block_device, attributes in six.iteritems(block_device_dict): _block_device = blockdevicemapping.EBSBlockDeviceType() for attribute, value in six.iteritems(attributes): setattr(_block_device, attribute, value) _block_device_map[block_device] = _block_device _bdms = [_block_device_map] # If a VPC is specified, then determine the secgroup id's within that VPC, not # within the default VPC. If a security group id is already part of the list, # convert_to_group_ids leaves that entry without attempting a lookup on it. if security_groups and (vpc_id or vpc_name): security_groups = __salt__['boto_secgroup.convert_to_group_ids']( security_groups, vpc_id=vpc_id, vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile ) lc = autoscale.LaunchConfiguration( name=name, image_id=image_id, key_name=key_name, security_groups=security_groups, user_data=user_data, instance_type=instance_type, kernel_id=kernel_id, ramdisk_id=ramdisk_id, block_device_mappings=_bdms, instance_monitoring=instance_monitoring, spot_price=spot_price, instance_profile_name=instance_profile_name, ebs_optimized=ebs_optimized, associate_public_ip_address=associate_public_ip_address, volume_type=volume_type, delete_on_termination=delete_on_termination, iops=iops, use_block_device_types=use_block_device_types) retries = 30 while True: try: conn.create_launch_configuration(lc) log.info('Created LC %s', name) return True except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) msg = 'Failed to create LC {0}'.format(name) log.error(msg) return False
python
def create_launch_configuration(name, image_id, key_name=None, vpc_id=None, vpc_name=None, security_groups=None, user_data=None, instance_type='m1.small', kernel_id=None, ramdisk_id=None, block_device_mappings=None, instance_monitoring=False, spot_price=None, instance_profile_name=None, ebs_optimized=False, associate_public_ip_address=None, volume_type=None, delete_on_termination=True, iops=None, use_block_device_types=False, region=None, key=None, keyid=None, profile=None): ''' Create a launch configuration. CLI example:: salt myminion boto_asg.create_launch_configuration mylc image_id=ami-0b9c9f62 key_name='mykey' security_groups='["mygroup"]' instance_type='c3.2xlarge' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) if isinstance(block_device_mappings, six.string_types): block_device_mappings = salt.utils.json.loads(block_device_mappings) _bdms = [] if block_device_mappings: # Boto requires objects for the mappings and the devices. _block_device_map = blockdevicemapping.BlockDeviceMapping() for block_device_dict in block_device_mappings: for block_device, attributes in six.iteritems(block_device_dict): _block_device = blockdevicemapping.EBSBlockDeviceType() for attribute, value in six.iteritems(attributes): setattr(_block_device, attribute, value) _block_device_map[block_device] = _block_device _bdms = [_block_device_map] # If a VPC is specified, then determine the secgroup id's within that VPC, not # within the default VPC. If a security group id is already part of the list, # convert_to_group_ids leaves that entry without attempting a lookup on it. if security_groups and (vpc_id or vpc_name): security_groups = __salt__['boto_secgroup.convert_to_group_ids']( security_groups, vpc_id=vpc_id, vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile ) lc = autoscale.LaunchConfiguration( name=name, image_id=image_id, key_name=key_name, security_groups=security_groups, user_data=user_data, instance_type=instance_type, kernel_id=kernel_id, ramdisk_id=ramdisk_id, block_device_mappings=_bdms, instance_monitoring=instance_monitoring, spot_price=spot_price, instance_profile_name=instance_profile_name, ebs_optimized=ebs_optimized, associate_public_ip_address=associate_public_ip_address, volume_type=volume_type, delete_on_termination=delete_on_termination, iops=iops, use_block_device_types=use_block_device_types) retries = 30 while True: try: conn.create_launch_configuration(lc) log.info('Created LC %s', name) return True except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) msg = 'Failed to create LC {0}'.format(name) log.error(msg) return False
[ "def", "create_launch_configuration", "(", "name", ",", "image_id", ",", "key_name", "=", "None", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "security_groups", "=", "None", ",", "user_data", "=", "None", ",", "instance_type", "=", "'m1.sm...
Create a launch configuration. CLI example:: salt myminion boto_asg.create_launch_configuration mylc image_id=ami-0b9c9f62 key_name='mykey' security_groups='["mygroup"]' instance_type='c3.2xlarge'
[ "Create", "a", "launch", "configuration", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L626-L699
train
saltstack/salt
salt/modules/boto_asg.py
delete_launch_configuration
def delete_launch_configuration(name, region=None, key=None, keyid=None, profile=None): ''' Delete a launch configuration. CLI example:: salt myminion boto_asg.delete_launch_configuration mylc ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: conn.delete_launch_configuration(name) log.info('Deleted LC %s', name) return True except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) msg = 'Failed to delete LC {0}'.format(name) log.error(msg) return False
python
def delete_launch_configuration(name, region=None, key=None, keyid=None, profile=None): ''' Delete a launch configuration. CLI example:: salt myminion boto_asg.delete_launch_configuration mylc ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: conn.delete_launch_configuration(name) log.info('Deleted LC %s', name) return True except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) msg = 'Failed to delete LC {0}'.format(name) log.error(msg) return False
[ "def", "delete_launch_configuration", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ...
Delete a launch configuration. CLI example:: salt myminion boto_asg.delete_launch_configuration mylc
[ "Delete", "a", "launch", "configuration", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L702-L727
train
saltstack/salt
salt/modules/boto_asg.py
get_scaling_policy_arn
def get_scaling_policy_arn(as_group, scaling_policy_name, region=None, key=None, keyid=None, profile=None): ''' Return the arn for a scaling policy in a specific autoscale group or None if not found. Mainly used as a helper method for boto_cloudwatch_alarm, for linking alarms to scaling policies. CLI Example:: salt '*' boto_asg.get_scaling_policy_arn mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries > 0: retries -= 1 try: policies = conn.get_all_policies(as_group=as_group) for policy in policies: if policy.name == scaling_policy_name: return policy.policy_arn log.error('Could not convert: %s', as_group) return None except boto.exception.BotoServerError as e: if e.error_code != 'Throttling': raise log.debug('Throttled by API, will retry in 5 seconds') time.sleep(5) log.error('Maximum number of retries exceeded') return None
python
def get_scaling_policy_arn(as_group, scaling_policy_name, region=None, key=None, keyid=None, profile=None): ''' Return the arn for a scaling policy in a specific autoscale group or None if not found. Mainly used as a helper method for boto_cloudwatch_alarm, for linking alarms to scaling policies. CLI Example:: salt '*' boto_asg.get_scaling_policy_arn mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries > 0: retries -= 1 try: policies = conn.get_all_policies(as_group=as_group) for policy in policies: if policy.name == scaling_policy_name: return policy.policy_arn log.error('Could not convert: %s', as_group) return None except boto.exception.BotoServerError as e: if e.error_code != 'Throttling': raise log.debug('Throttled by API, will retry in 5 seconds') time.sleep(5) log.error('Maximum number of retries exceeded') return None
[ "def", "get_scaling_policy_arn", "(", "as_group", ",", "scaling_policy_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", "...
Return the arn for a scaling policy in a specific autoscale group or None if not found. Mainly used as a helper method for boto_cloudwatch_alarm, for linking alarms to scaling policies. CLI Example:: salt '*' boto_asg.get_scaling_policy_arn mygroup mypolicy
[ "Return", "the", "arn", "for", "a", "scaling", "policy", "in", "a", "specific", "autoscale", "group", "or", "None", "if", "not", "found", ".", "Mainly", "used", "as", "a", "helper", "method", "for", "boto_cloudwatch_alarm", "for", "linking", "alarms", "to", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L730-L759
train
saltstack/salt
salt/modules/boto_asg.py
get_all_groups
def get_all_groups(region=None, key=None, keyid=None, profile=None): ''' Return all AutoScale Groups visible in the account (as a list of boto.ec2.autoscale.group.AutoScalingGroup). .. versionadded:: 2016.11.0 CLI example: .. code-block:: bash salt-call boto_asg.get_all_groups region=us-east-1 --output yaml ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: next_token = '' asgs = [] while next_token is not None: ret = conn.get_all_groups(next_token=next_token) asgs += [a for a in ret] next_token = ret.next_token return asgs except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return []
python
def get_all_groups(region=None, key=None, keyid=None, profile=None): ''' Return all AutoScale Groups visible in the account (as a list of boto.ec2.autoscale.group.AutoScalingGroup). .. versionadded:: 2016.11.0 CLI example: .. code-block:: bash salt-call boto_asg.get_all_groups region=us-east-1 --output yaml ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: next_token = '' asgs = [] while next_token is not None: ret = conn.get_all_groups(next_token=next_token) asgs += [a for a in ret] next_token = ret.next_token return asgs except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return []
[ "def", "get_all_groups", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyi...
Return all AutoScale Groups visible in the account (as a list of boto.ec2.autoscale.group.AutoScalingGroup). .. versionadded:: 2016.11.0 CLI example: .. code-block:: bash salt-call boto_asg.get_all_groups region=us-east-1 --output yaml
[ "Return", "all", "AutoScale", "Groups", "visible", "in", "the", "account", "(", "as", "a", "list", "of", "boto", ".", "ec2", ".", "autoscale", ".", "group", ".", "AutoScalingGroup", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L762-L794
train
saltstack/salt
salt/modules/boto_asg.py
list_groups
def list_groups(region=None, key=None, keyid=None, profile=None): ''' Return all AutoScale Groups visible in the account (as a list of names). .. versionadded:: 2016.11.0 CLI example: .. code-block:: bash salt-call boto_asg.list_groups region=us-east-1 ''' return [a.name for a in get_all_groups(region=region, key=key, keyid=keyid, profile=profile)]
python
def list_groups(region=None, key=None, keyid=None, profile=None): ''' Return all AutoScale Groups visible in the account (as a list of names). .. versionadded:: 2016.11.0 CLI example: .. code-block:: bash salt-call boto_asg.list_groups region=us-east-1 ''' return [a.name for a in get_all_groups(region=region, key=key, keyid=keyid, profile=profile)]
[ "def", "list_groups", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "[", "a", ".", "name", "for", "a", "in", "get_all_groups", "(", "region", "=", "region", ",", "ke...
Return all AutoScale Groups visible in the account (as a list of names). .. versionadded:: 2016.11.0 CLI example: .. code-block:: bash salt-call boto_asg.list_groups region=us-east-1
[ "Return", "all", "AutoScale", "Groups", "visible", "in", "the", "account", "(", "as", "a", "list", "of", "names", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L797-L811
train
saltstack/salt
salt/modules/boto_asg.py
get_instances
def get_instances(name, lifecycle_state="InService", health_status="Healthy", attribute="private_ip_address", attributes=None, region=None, key=None, keyid=None, profile=None): ''' return attribute of all instances in the named autoscale group. CLI example:: salt-call boto_asg.get_instances my_autoscale_group_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ec2_conn = _get_ec2_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: asgs = conn.get_all_groups(names=[name]) break except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return False if len(asgs) != 1: log.debug("name '%s' returns multiple ASGs: %s", name, [asg.name for asg in asgs]) return False asg = asgs[0] instance_ids = [] # match lifecycle_state and health_status for i in asg.instances: if lifecycle_state is not None and i.lifecycle_state != lifecycle_state: continue if health_status is not None and i.health_status != health_status: continue instance_ids.append(i.instance_id) # get full instance info, so that we can return the attribute instances = ec2_conn.get_only_instances(instance_ids=instance_ids) if attributes: return [[_convert_attribute(instance, attr) for attr in attributes] for instance in instances] else: # properly handle case when not all instances have the requested attribute return [_convert_attribute(instance, attribute) for instance in instances if getattr(instance, attribute)]
python
def get_instances(name, lifecycle_state="InService", health_status="Healthy", attribute="private_ip_address", attributes=None, region=None, key=None, keyid=None, profile=None): ''' return attribute of all instances in the named autoscale group. CLI example:: salt-call boto_asg.get_instances my_autoscale_group_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ec2_conn = _get_ec2_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: asgs = conn.get_all_groups(names=[name]) break except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, retrying in 5 seconds...') time.sleep(5) retries -= 1 continue log.error(e) return False if len(asgs) != 1: log.debug("name '%s' returns multiple ASGs: %s", name, [asg.name for asg in asgs]) return False asg = asgs[0] instance_ids = [] # match lifecycle_state and health_status for i in asg.instances: if lifecycle_state is not None and i.lifecycle_state != lifecycle_state: continue if health_status is not None and i.health_status != health_status: continue instance_ids.append(i.instance_id) # get full instance info, so that we can return the attribute instances = ec2_conn.get_only_instances(instance_ids=instance_ids) if attributes: return [[_convert_attribute(instance, attr) for attr in attributes] for instance in instances] else: # properly handle case when not all instances have the requested attribute return [_convert_attribute(instance, attribute) for instance in instances if getattr(instance, attribute)]
[ "def", "get_instances", "(", "name", ",", "lifecycle_state", "=", "\"InService\"", ",", "health_status", "=", "\"Healthy\"", ",", "attribute", "=", "\"private_ip_address\"", ",", "attributes", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", "...
return attribute of all instances in the named autoscale group. CLI example:: salt-call boto_asg.get_instances my_autoscale_group_name
[ "return", "attribute", "of", "all", "instances", "in", "the", "named", "autoscale", "group", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L814-L858
train
saltstack/salt
salt/modules/boto_asg.py
exit_standby
def exit_standby(name, instance_ids, should_decrement_desired_capacity=False, region=None, key=None, keyid=None, profile=None): ''' Exit desired instances from StandBy mode .. versionadded:: 2016.11.0 CLI example:: salt-call boto_asg.exit_standby my_autoscale_group_name '["i-xxxxxx"]' ''' conn = _get_conn_autoscaling_boto3( region=region, key=key, keyid=keyid, profile=profile) try: response = conn.exit_standby( InstanceIds=instance_ids, AutoScalingGroupName=name) except ClientError as e: err = __utils__['boto3.get_error'](e) if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException': return {'exists': False} return {'error': err} return all(activity['StatusCode'] != 'Failed' for activity in response['Activities'])
python
def exit_standby(name, instance_ids, should_decrement_desired_capacity=False, region=None, key=None, keyid=None, profile=None): ''' Exit desired instances from StandBy mode .. versionadded:: 2016.11.0 CLI example:: salt-call boto_asg.exit_standby my_autoscale_group_name '["i-xxxxxx"]' ''' conn = _get_conn_autoscaling_boto3( region=region, key=key, keyid=keyid, profile=profile) try: response = conn.exit_standby( InstanceIds=instance_ids, AutoScalingGroupName=name) except ClientError as e: err = __utils__['boto3.get_error'](e) if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException': return {'exists': False} return {'error': err} return all(activity['StatusCode'] != 'Failed' for activity in response['Activities'])
[ "def", "exit_standby", "(", "name", ",", "instance_ids", ",", "should_decrement_desired_capacity", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn_...
Exit desired instances from StandBy mode .. versionadded:: 2016.11.0 CLI example:: salt-call boto_asg.exit_standby my_autoscale_group_name '["i-xxxxxx"]'
[ "Exit", "desired", "instances", "from", "StandBy", "mode" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L895-L918
train
saltstack/salt
salt/modules/scsi.py
ls_
def ls_(get_size=True): ''' List SCSI devices, with details CLI Examples: .. code-block:: bash salt '*' scsi.ls salt '*' scsi.ls get_size=False get_size : True Get the size information for scsi devices. This option should be set to False for older OS distributions (RHEL6 and older) due to lack of support for the '-s' option in lsscsi. .. versionadded:: 2015.5.10 ''' if not salt.utils.path.which('lsscsi'): __context__['retcode'] = 1 return 'scsi.ls not available - lsscsi command not found' if get_size: cmd = 'lsscsi -dLsv' else: cmd = 'lsscsi -dLv' ret = {} res = __salt__['cmd.run_all'](cmd) rc = res.get('retcode', -1) if rc != 0: __context__['retcode'] = rc error = res.get('stderr', '').split('\n')[0] if error == "lsscsi: invalid option -- 's'": return '{0} - try get_size=False'.format(error) return res.get('stderr', '').split('\n')[0] data = res.get('stdout', '') for line in data.splitlines(): if line.startswith('['): size = None major = None minor = None comps = line.strip().split() key = comps[0] if get_size: size = comps.pop() majmin = comps.pop() if majmin.startswith('['): major, minor = majmin.replace('[', '').replace(']', '').split(':') device = comps.pop() model = ' '.join(comps[3:]) ret[key] = { 'lun': key.replace('[', '').replace(']', ''), 'size': size, 'major': major, 'minor': minor, 'device': device, 'model': model, } elif line.startswith(' '): if line.strip().startswith('dir'): comps = line.strip().split() ret[key]['dir'] = [ comps[1], comps[2].replace('[', '').replace(']', '') ] else: comps = line.strip().split('=') ret[key][comps[0]] = comps[1] return ret
python
def ls_(get_size=True): ''' List SCSI devices, with details CLI Examples: .. code-block:: bash salt '*' scsi.ls salt '*' scsi.ls get_size=False get_size : True Get the size information for scsi devices. This option should be set to False for older OS distributions (RHEL6 and older) due to lack of support for the '-s' option in lsscsi. .. versionadded:: 2015.5.10 ''' if not salt.utils.path.which('lsscsi'): __context__['retcode'] = 1 return 'scsi.ls not available - lsscsi command not found' if get_size: cmd = 'lsscsi -dLsv' else: cmd = 'lsscsi -dLv' ret = {} res = __salt__['cmd.run_all'](cmd) rc = res.get('retcode', -1) if rc != 0: __context__['retcode'] = rc error = res.get('stderr', '').split('\n')[0] if error == "lsscsi: invalid option -- 's'": return '{0} - try get_size=False'.format(error) return res.get('stderr', '').split('\n')[0] data = res.get('stdout', '') for line in data.splitlines(): if line.startswith('['): size = None major = None minor = None comps = line.strip().split() key = comps[0] if get_size: size = comps.pop() majmin = comps.pop() if majmin.startswith('['): major, minor = majmin.replace('[', '').replace(']', '').split(':') device = comps.pop() model = ' '.join(comps[3:]) ret[key] = { 'lun': key.replace('[', '').replace(']', ''), 'size': size, 'major': major, 'minor': minor, 'device': device, 'model': model, } elif line.startswith(' '): if line.strip().startswith('dir'): comps = line.strip().split() ret[key]['dir'] = [ comps[1], comps[2].replace('[', '').replace(']', '') ] else: comps = line.strip().split('=') ret[key][comps[0]] = comps[1] return ret
[ "def", "ls_", "(", "get_size", "=", "True", ")", ":", "if", "not", "salt", ".", "utils", ".", "path", ".", "which", "(", "'lsscsi'", ")", ":", "__context__", "[", "'retcode'", "]", "=", "1", "return", "'scsi.ls not available - lsscsi command not found'", "if...
List SCSI devices, with details CLI Examples: .. code-block:: bash salt '*' scsi.ls salt '*' scsi.ls get_size=False get_size : True Get the size information for scsi devices. This option should be set to False for older OS distributions (RHEL6 and older) due to lack of support for the '-s' option in lsscsi. .. versionadded:: 2015.5.10
[ "List", "SCSI", "devices", "with", "details" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/scsi.py#L18-L89
train
saltstack/salt
salt/modules/scsi.py
rescan_all
def rescan_all(host): ''' List scsi devices CLI Example: .. code-block:: bash salt '*' scsi.rescan_all 0 ''' if os.path.isdir('/sys/class/scsi_host/host{0}'.format(host)): cmd = 'echo "- - -" > /sys/class/scsi_host/host{0}/scan'.format(host) else: return 'Host {0} does not exist'.format(host) return __salt__['cmd.run'](cmd).splitlines()
python
def rescan_all(host): ''' List scsi devices CLI Example: .. code-block:: bash salt '*' scsi.rescan_all 0 ''' if os.path.isdir('/sys/class/scsi_host/host{0}'.format(host)): cmd = 'echo "- - -" > /sys/class/scsi_host/host{0}/scan'.format(host) else: return 'Host {0} does not exist'.format(host) return __salt__['cmd.run'](cmd).splitlines()
[ "def", "rescan_all", "(", "host", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "'/sys/class/scsi_host/host{0}'", ".", "format", "(", "host", ")", ")", ":", "cmd", "=", "'echo \"- - -\" > /sys/class/scsi_host/host{0}/scan'", ".", "format", "(", "host", ...
List scsi devices CLI Example: .. code-block:: bash salt '*' scsi.rescan_all 0
[ "List", "scsi", "devices" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/scsi.py#L92-L106
train
saltstack/salt
salt/states/esxcluster.py
_get_vsan_datastore
def _get_vsan_datastore(si, cluster_name): '''Retrieves the vsan_datastore''' log.trace('Retrieving vsan datastore') vsan_datastores = [ds for ds in __salt__['vsphere.list_datastores_via_proxy']( service_instance=si) if ds['type'] == 'vsan'] if not vsan_datastores: raise salt.exceptions.VMwareObjectRetrievalError( 'No vSAN datastores where retrieved for cluster ' '\'{0}\''.format(cluster_name)) return vsan_datastores[0]
python
def _get_vsan_datastore(si, cluster_name): '''Retrieves the vsan_datastore''' log.trace('Retrieving vsan datastore') vsan_datastores = [ds for ds in __salt__['vsphere.list_datastores_via_proxy']( service_instance=si) if ds['type'] == 'vsan'] if not vsan_datastores: raise salt.exceptions.VMwareObjectRetrievalError( 'No vSAN datastores where retrieved for cluster ' '\'{0}\''.format(cluster_name)) return vsan_datastores[0]
[ "def", "_get_vsan_datastore", "(", "si", ",", "cluster_name", ")", ":", "log", ".", "trace", "(", "'Retrieving vsan datastore'", ")", "vsan_datastores", "=", "[", "ds", "for", "ds", "in", "__salt__", "[", "'vsphere.list_datastores_via_proxy'", "]", "(", "service_i...
Retrieves the vsan_datastore
[ "Retrieves", "the", "vsan_datastore" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxcluster.py#L95-L108
train
saltstack/salt
salt/states/esxcluster.py
cluster_configured
def cluster_configured(name, cluster_config): ''' Configures a cluster. Creates a new cluster, if it doesn't exist on the vCenter or reconfigures it if configured differently Supported proxies: esxdatacenter, esxcluster name Name of the state. If the state is run in by an ``esxdatacenter`` proxy, it will be the name of the cluster. cluster_config Configuration applied to the cluster. Complex datastructure following the ESXClusterConfigSchema. Valid example is: .. code-block::yaml drs: default_vm_behavior: fullyAutomated enabled: true vmotion_rate: 3 ha: admission_control _enabled: false default_vm_settings: isolation_response: powerOff restart_priority: medium enabled: true hb_ds_candidate_policy: userSelectedDs host_monitoring: enabled options: - key: das.ignoreinsufficienthbdatastore value: 'true' vm_monitoring: vmMonitoringDisabled vm_swap_placement: vmDirectory vsan: auto_claim_storage: false compression_enabled: true dedup_enabled: true enabled: true ''' proxy_type = __salt__['vsphere.get_proxy_type']() if proxy_type == 'esxdatacenter': cluster_name, datacenter_name = \ name, __salt__['esxdatacenter.get_details']()['datacenter'] elif proxy_type == 'esxcluster': cluster_name, datacenter_name = \ __salt__['esxcluster.get_details']()['cluster'], \ __salt__['esxcluster.get_details']()['datacenter'] else: raise salt.exceptions.CommandExecutionError('Unsupported proxy {0}' ''.format(proxy_type)) log.info('Running %s for cluster \'%s\' in datacenter \'%s\'', name, cluster_name, datacenter_name) cluster_dict = cluster_config log.trace('cluster_dict = %s', cluster_dict) changes_required = False ret = {'name': name, 'changes': {}, 'result': None, 'comment': 'Default'} comments = [] changes = {} changes_required = False try: log.trace('Validating cluster_configured state input') schema = ESXClusterConfigSchema.serialize() log.trace('schema = %s', schema) try: jsonschema.validate(cluster_dict, schema) except jsonschema.exceptions.ValidationError as exc: raise salt.exceptions.InvalidESXClusterPayloadError(exc) current = None si = __salt__['vsphere.get_service_instance_via_proxy']() try: current = __salt__['vsphere.list_cluster'](datacenter_name, cluster_name, service_instance=si) except salt.exceptions.VMwareObjectRetrievalError: changes_required = True if __opts__['test']: comments.append('State {0} will create cluster ' '\'{1}\' in datacenter \'{2}\'.' ''.format(name, cluster_name, datacenter_name)) log.info(comments[-1]) __salt__['vsphere.disconnect'](si) ret.update({'result': None, 'comment': '\n'.join(comments)}) return ret log.trace('Creating cluster \'%s\' in datacenter \'%s\'. ', cluster_name, datacenter_name) __salt__['vsphere.create_cluster'](cluster_dict, datacenter_name, cluster_name, service_instance=si) comments.append('Created cluster \'{0}\' in datacenter \'{1}\'' ''.format(cluster_name, datacenter_name)) log.info(comments[-1]) changes.update({'new': cluster_dict}) if current: # Cluster already exists # We need to handle lists sepparately ldiff = None if 'ha' in cluster_dict and 'options' in cluster_dict['ha']: ldiff = list_diff(current.get('ha', {}).get('options', []), cluster_dict.get('ha', {}).get('options', []), 'key') log.trace('options diffs = %s', ldiff.diffs) # Remove options if exist del cluster_dict['ha']['options'] if 'ha' in current and 'options' in current['ha']: del current['ha']['options'] diff = recursive_diff(current, cluster_dict) log.trace('diffs = %s', diff.diffs) if not (diff.diffs or (ldiff and ldiff.diffs)): # No differences comments.append('Cluster \'{0}\' in datacenter \'{1}\' is up ' 'to date. Nothing to be done.' ''.format(cluster_name, datacenter_name)) log.info(comments[-1]) else: changes_required = True changes_str = '' if diff.diffs: changes_str = '{0}{1}'.format(changes_str, diff.changes_str) if ldiff and ldiff.diffs: changes_str = '{0}\nha:\n options:\n{1}'.format( changes_str, '\n'.join([' {0}'.format(l) for l in ldiff.changes_str2.split('\n')])) # Apply the changes if __opts__['test']: comments.append( 'State {0} will update cluster \'{1}\' ' 'in datacenter \'{2}\':\n{3}' ''.format(name, cluster_name, datacenter_name, changes_str)) else: new_values = diff.new_values old_values = diff.old_values if ldiff and ldiff.new_values: dictupdate.update( new_values, {'ha': {'options': ldiff.new_values}}) if ldiff and ldiff.old_values: dictupdate.update( old_values, {'ha': {'options': ldiff.old_values}}) log.trace('new_values = %s', new_values) __salt__['vsphere.update_cluster'](new_values, datacenter_name, cluster_name, service_instance=si) comments.append('Updated cluster \'{0}\' in datacenter ' '\'{1}\''.format(cluster_name, datacenter_name)) log.info(comments[-1]) changes.update({'new': new_values, 'old': old_values}) __salt__['vsphere.disconnect'](si) ret_status = True if __opts__['test'] and changes_required: ret_status = None ret.update({'result': ret_status, 'comment': '\n'.join(comments), 'changes': changes}) return ret except salt.exceptions.CommandExecutionError as exc: log.exception('Encountered error') if si: __salt__['vsphere.disconnect'](si) ret.update({ 'result': False, 'comment': six.text_type(exc)}) return ret
python
def cluster_configured(name, cluster_config): ''' Configures a cluster. Creates a new cluster, if it doesn't exist on the vCenter or reconfigures it if configured differently Supported proxies: esxdatacenter, esxcluster name Name of the state. If the state is run in by an ``esxdatacenter`` proxy, it will be the name of the cluster. cluster_config Configuration applied to the cluster. Complex datastructure following the ESXClusterConfigSchema. Valid example is: .. code-block::yaml drs: default_vm_behavior: fullyAutomated enabled: true vmotion_rate: 3 ha: admission_control _enabled: false default_vm_settings: isolation_response: powerOff restart_priority: medium enabled: true hb_ds_candidate_policy: userSelectedDs host_monitoring: enabled options: - key: das.ignoreinsufficienthbdatastore value: 'true' vm_monitoring: vmMonitoringDisabled vm_swap_placement: vmDirectory vsan: auto_claim_storage: false compression_enabled: true dedup_enabled: true enabled: true ''' proxy_type = __salt__['vsphere.get_proxy_type']() if proxy_type == 'esxdatacenter': cluster_name, datacenter_name = \ name, __salt__['esxdatacenter.get_details']()['datacenter'] elif proxy_type == 'esxcluster': cluster_name, datacenter_name = \ __salt__['esxcluster.get_details']()['cluster'], \ __salt__['esxcluster.get_details']()['datacenter'] else: raise salt.exceptions.CommandExecutionError('Unsupported proxy {0}' ''.format(proxy_type)) log.info('Running %s for cluster \'%s\' in datacenter \'%s\'', name, cluster_name, datacenter_name) cluster_dict = cluster_config log.trace('cluster_dict = %s', cluster_dict) changes_required = False ret = {'name': name, 'changes': {}, 'result': None, 'comment': 'Default'} comments = [] changes = {} changes_required = False try: log.trace('Validating cluster_configured state input') schema = ESXClusterConfigSchema.serialize() log.trace('schema = %s', schema) try: jsonschema.validate(cluster_dict, schema) except jsonschema.exceptions.ValidationError as exc: raise salt.exceptions.InvalidESXClusterPayloadError(exc) current = None si = __salt__['vsphere.get_service_instance_via_proxy']() try: current = __salt__['vsphere.list_cluster'](datacenter_name, cluster_name, service_instance=si) except salt.exceptions.VMwareObjectRetrievalError: changes_required = True if __opts__['test']: comments.append('State {0} will create cluster ' '\'{1}\' in datacenter \'{2}\'.' ''.format(name, cluster_name, datacenter_name)) log.info(comments[-1]) __salt__['vsphere.disconnect'](si) ret.update({'result': None, 'comment': '\n'.join(comments)}) return ret log.trace('Creating cluster \'%s\' in datacenter \'%s\'. ', cluster_name, datacenter_name) __salt__['vsphere.create_cluster'](cluster_dict, datacenter_name, cluster_name, service_instance=si) comments.append('Created cluster \'{0}\' in datacenter \'{1}\'' ''.format(cluster_name, datacenter_name)) log.info(comments[-1]) changes.update({'new': cluster_dict}) if current: # Cluster already exists # We need to handle lists sepparately ldiff = None if 'ha' in cluster_dict and 'options' in cluster_dict['ha']: ldiff = list_diff(current.get('ha', {}).get('options', []), cluster_dict.get('ha', {}).get('options', []), 'key') log.trace('options diffs = %s', ldiff.diffs) # Remove options if exist del cluster_dict['ha']['options'] if 'ha' in current and 'options' in current['ha']: del current['ha']['options'] diff = recursive_diff(current, cluster_dict) log.trace('diffs = %s', diff.diffs) if not (diff.diffs or (ldiff and ldiff.diffs)): # No differences comments.append('Cluster \'{0}\' in datacenter \'{1}\' is up ' 'to date. Nothing to be done.' ''.format(cluster_name, datacenter_name)) log.info(comments[-1]) else: changes_required = True changes_str = '' if diff.diffs: changes_str = '{0}{1}'.format(changes_str, diff.changes_str) if ldiff and ldiff.diffs: changes_str = '{0}\nha:\n options:\n{1}'.format( changes_str, '\n'.join([' {0}'.format(l) for l in ldiff.changes_str2.split('\n')])) # Apply the changes if __opts__['test']: comments.append( 'State {0} will update cluster \'{1}\' ' 'in datacenter \'{2}\':\n{3}' ''.format(name, cluster_name, datacenter_name, changes_str)) else: new_values = diff.new_values old_values = diff.old_values if ldiff and ldiff.new_values: dictupdate.update( new_values, {'ha': {'options': ldiff.new_values}}) if ldiff and ldiff.old_values: dictupdate.update( old_values, {'ha': {'options': ldiff.old_values}}) log.trace('new_values = %s', new_values) __salt__['vsphere.update_cluster'](new_values, datacenter_name, cluster_name, service_instance=si) comments.append('Updated cluster \'{0}\' in datacenter ' '\'{1}\''.format(cluster_name, datacenter_name)) log.info(comments[-1]) changes.update({'new': new_values, 'old': old_values}) __salt__['vsphere.disconnect'](si) ret_status = True if __opts__['test'] and changes_required: ret_status = None ret.update({'result': ret_status, 'comment': '\n'.join(comments), 'changes': changes}) return ret except salt.exceptions.CommandExecutionError as exc: log.exception('Encountered error') if si: __salt__['vsphere.disconnect'](si) ret.update({ 'result': False, 'comment': six.text_type(exc)}) return ret
[ "def", "cluster_configured", "(", "name", ",", "cluster_config", ")", ":", "proxy_type", "=", "__salt__", "[", "'vsphere.get_proxy_type'", "]", "(", ")", "if", "proxy_type", "==", "'esxdatacenter'", ":", "cluster_name", ",", "datacenter_name", "=", "name", ",", ...
Configures a cluster. Creates a new cluster, if it doesn't exist on the vCenter or reconfigures it if configured differently Supported proxies: esxdatacenter, esxcluster name Name of the state. If the state is run in by an ``esxdatacenter`` proxy, it will be the name of the cluster. cluster_config Configuration applied to the cluster. Complex datastructure following the ESXClusterConfigSchema. Valid example is: .. code-block::yaml drs: default_vm_behavior: fullyAutomated enabled: true vmotion_rate: 3 ha: admission_control _enabled: false default_vm_settings: isolation_response: powerOff restart_priority: medium enabled: true hb_ds_candidate_policy: userSelectedDs host_monitoring: enabled options: - key: das.ignoreinsufficienthbdatastore value: 'true' vm_monitoring: vmMonitoringDisabled vm_swap_placement: vmDirectory vsan: auto_claim_storage: false compression_enabled: true dedup_enabled: true enabled: true
[ "Configures", "a", "cluster", ".", "Creates", "a", "new", "cluster", "if", "it", "doesn", "t", "exist", "on", "the", "vCenter", "or", "reconfigures", "it", "if", "configured", "differently" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxcluster.py#L111-L285
train
saltstack/salt
salt/states/esxcluster.py
vsan_datastore_configured
def vsan_datastore_configured(name, datastore_name): ''' Configures the cluster's VSAN datastore WARNING: The VSAN datastore is created automatically after the first ESXi host is added to the cluster; the state assumes that the datastore exists and errors if it doesn't. ''' cluster_name, datacenter_name = \ __salt__['esxcluster.get_details']()['cluster'], \ __salt__['esxcluster.get_details']()['datacenter'] display_name = '{0}/{1}'.format(datacenter_name, cluster_name) log.info('Running vsan_datastore_configured for \'%s\'', display_name) ret = {'name': name, 'changes': {}, 'result': None, 'comment': 'Default'} comments = [] changes = {} changes_required = False try: si = __salt__['vsphere.get_service_instance_via_proxy']() # Checking if we need to rename the vsan datastore vsan_ds = _get_vsan_datastore(si, cluster_name) if vsan_ds['name'] == datastore_name: comments.append('vSAN datastore is correctly named \'{0}\'. ' 'Nothing to be done.'.format(vsan_ds['name'])) log.info(comments[-1]) else: # vsan_ds needs to be updated changes_required = True if __opts__['test']: comments.append('State {0} will rename the vSAN datastore to ' '\'{1}\'.'.format(name, datastore_name)) log.info(comments[-1]) else: log.trace('Renaming vSAN datastore \'%s\' to \'%s\'', vsan_ds['name'], datastore_name) __salt__['vsphere.rename_datastore']( datastore_name=vsan_ds['name'], new_datastore_name=datastore_name, service_instance=si) comments.append('Renamed vSAN datastore to \'{0}\'.' ''.format(datastore_name)) changes = {'vsan_datastore': {'new': {'name': datastore_name}, 'old': {'name': vsan_ds['name']}}} log.info(comments[-1]) __salt__['vsphere.disconnect'](si) ret.update({'result': True if (not changes_required) else None if __opts__['test'] else True, 'comment': '\n'.join(comments), 'changes': changes}) return ret except salt.exceptions.CommandExecutionError as exc: log.exception('Encountered error') if si: __salt__['vsphere.disconnect'](si) ret.update({ 'result': False, 'comment': exc.strerror}) return ret
python
def vsan_datastore_configured(name, datastore_name): ''' Configures the cluster's VSAN datastore WARNING: The VSAN datastore is created automatically after the first ESXi host is added to the cluster; the state assumes that the datastore exists and errors if it doesn't. ''' cluster_name, datacenter_name = \ __salt__['esxcluster.get_details']()['cluster'], \ __salt__['esxcluster.get_details']()['datacenter'] display_name = '{0}/{1}'.format(datacenter_name, cluster_name) log.info('Running vsan_datastore_configured for \'%s\'', display_name) ret = {'name': name, 'changes': {}, 'result': None, 'comment': 'Default'} comments = [] changes = {} changes_required = False try: si = __salt__['vsphere.get_service_instance_via_proxy']() # Checking if we need to rename the vsan datastore vsan_ds = _get_vsan_datastore(si, cluster_name) if vsan_ds['name'] == datastore_name: comments.append('vSAN datastore is correctly named \'{0}\'. ' 'Nothing to be done.'.format(vsan_ds['name'])) log.info(comments[-1]) else: # vsan_ds needs to be updated changes_required = True if __opts__['test']: comments.append('State {0} will rename the vSAN datastore to ' '\'{1}\'.'.format(name, datastore_name)) log.info(comments[-1]) else: log.trace('Renaming vSAN datastore \'%s\' to \'%s\'', vsan_ds['name'], datastore_name) __salt__['vsphere.rename_datastore']( datastore_name=vsan_ds['name'], new_datastore_name=datastore_name, service_instance=si) comments.append('Renamed vSAN datastore to \'{0}\'.' ''.format(datastore_name)) changes = {'vsan_datastore': {'new': {'name': datastore_name}, 'old': {'name': vsan_ds['name']}}} log.info(comments[-1]) __salt__['vsphere.disconnect'](si) ret.update({'result': True if (not changes_required) else None if __opts__['test'] else True, 'comment': '\n'.join(comments), 'changes': changes}) return ret except salt.exceptions.CommandExecutionError as exc: log.exception('Encountered error') if si: __salt__['vsphere.disconnect'](si) ret.update({ 'result': False, 'comment': exc.strerror}) return ret
[ "def", "vsan_datastore_configured", "(", "name", ",", "datastore_name", ")", ":", "cluster_name", ",", "datacenter_name", "=", "__salt__", "[", "'esxcluster.get_details'", "]", "(", ")", "[", "'cluster'", "]", ",", "__salt__", "[", "'esxcluster.get_details'", "]", ...
Configures the cluster's VSAN datastore WARNING: The VSAN datastore is created automatically after the first ESXi host is added to the cluster; the state assumes that the datastore exists and errors if it doesn't.
[ "Configures", "the", "cluster", "s", "VSAN", "datastore" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxcluster.py#L288-L350
train
saltstack/salt
salt/states/esxcluster.py
licenses_configured
def licenses_configured(name, licenses=None): ''' Configures licenses on the cluster entity Checks if each license exists on the server: - if it doesn't, it creates it Check if license is assigned to the cluster: - if it's not assigned to the cluster: - assign it to the cluster if there is space - error if there's no space - if it's assigned to the cluster nothing needs to be done ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': 'Default'} if not licenses: raise salt.exceptions.ArgumentValueError('No licenses provided') cluster_name, datacenter_name = \ __salt__['esxcluster.get_details']()['cluster'], \ __salt__['esxcluster.get_details']()['datacenter'] display_name = '{0}/{1}'.format(datacenter_name, cluster_name) log.info('Running licenses configured for \'%s\'', display_name) log.trace('licenses = %s', licenses) entity = {'type': 'cluster', 'datacenter': datacenter_name, 'cluster': cluster_name} log.trace('entity = %s', entity) comments = [] changes = {} old_licenses = [] new_licenses = [] has_errors = False needs_changes = False try: # Validate licenses log.trace('Validating licenses') schema = LicenseSchema.serialize() try: jsonschema.validate({'licenses': licenses}, schema) except jsonschema.exceptions.ValidationError as exc: raise salt.exceptions.InvalidLicenseError(exc) si = __salt__['vsphere.get_service_instance_via_proxy']() # Retrieve licenses existing_licenses = __salt__['vsphere.list_licenses']( service_instance=si) remaining_licenses = existing_licenses[:] # Cycle through licenses for license_name, license in licenses.items(): # Check if license already exists filtered_licenses = [l for l in existing_licenses if l['key'] == license] # TODO Update license description - not of interest right now if not filtered_licenses: # License doesn't exist - add and assign to cluster needs_changes = True if __opts__['test']: # If it doesn't exist it clearly needs to be assigned as # well so we can stop the check here comments.append('State {0} will add license \'{1}\', ' 'and assign it to cluster \'{2}\'.' ''.format(name, license_name, display_name)) log.info(comments[-1]) continue else: try: existing_license = __salt__['vsphere.add_license']( key=license, description=license_name, service_instance=si) except salt.exceptions.VMwareApiError as ex: comments.append(ex.err_msg) log.error(comments[-1]) has_errors = True continue comments.append('Added license \'{0}\'.' ''.format(license_name)) log.info(comments[-1]) else: # License exists let's check if it's assigned to the cluster comments.append('License \'{0}\' already exists. ' 'Nothing to be done.'.format(license_name)) log.info(comments[-1]) existing_license = filtered_licenses[0] log.trace('Checking licensed entities...') assigned_licenses = __salt__['vsphere.list_assigned_licenses']( entity=entity, entity_display_name=display_name, service_instance=si) # Checking if any of the licenses already assigned have the same # name as the new license; the already assigned license would be # replaced by the new license # # Licenses with different names but matching features would be # replaced as well, but searching for those would be very complex # # the name check if good enough for now already_assigned_license = assigned_licenses[0] if \ assigned_licenses else None if already_assigned_license and \ already_assigned_license['key'] == license: # License is already assigned to entity comments.append('License \'{0}\' already assigned to ' 'cluster \'{1}\'. Nothing to be done.' ''.format(license_name, display_name)) log.info(comments[-1]) continue needs_changes = True # License needs to be assigned to entity if existing_license['capacity'] <= existing_license['used']: # License is already fully used comments.append('Cannot assign license \'{0}\' to cluster ' '\'{1}\'. No free capacity available.' ''.format(license_name, display_name)) log.error(comments[-1]) has_errors = True continue # Assign license if __opts__['test']: comments.append('State {0} will assign license \'{1}\' ' 'to cluster \'{2}\'.'.format( name, license_name, display_name)) log.info(comments[-1]) else: try: __salt__['vsphere.assign_license']( license_key=license, license_name=license_name, entity=entity, entity_display_name=display_name, service_instance=si) except salt.exceptions.VMwareApiError as ex: comments.append(ex.err_msg) log.error(comments[-1]) has_errors = True continue comments.append('Assigned license \'{0}\' to cluster \'{1}\'.' ''.format(license_name, display_name)) log.info(comments[-1]) # Note: Because the already_assigned_license was retrieved # from the assignment license manager it doesn't have a used # value - that's a limitation from VMware. The license would # need to be retrieved again from the license manager to get # the value # Hide license keys assigned_license = __salt__['vsphere.list_assigned_licenses']( entity=entity, entity_display_name=display_name, service_instance=si)[0] assigned_license['key'] = '<hidden>' if already_assigned_license: already_assigned_license['key'] = '<hidden>' if already_assigned_license and \ already_assigned_license['capacity'] == sys.maxsize: already_assigned_license['capacity'] = 'Unlimited' changes[license_name] = {'new': assigned_license, 'old': already_assigned_license} continue __salt__['vsphere.disconnect'](si) ret.update({'result': True if (not needs_changes) else None if __opts__['test'] else False if has_errors else True, 'comment': '\n'.join(comments), 'changes': changes if not __opts__['test'] else {}}) return ret except salt.exceptions.CommandExecutionError as exc: log.exception('Encountered error') if si: __salt__['vsphere.disconnect'](si) ret.update({ 'result': False, 'comment': exc.strerror}) return ret
python
def licenses_configured(name, licenses=None): ''' Configures licenses on the cluster entity Checks if each license exists on the server: - if it doesn't, it creates it Check if license is assigned to the cluster: - if it's not assigned to the cluster: - assign it to the cluster if there is space - error if there's no space - if it's assigned to the cluster nothing needs to be done ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': 'Default'} if not licenses: raise salt.exceptions.ArgumentValueError('No licenses provided') cluster_name, datacenter_name = \ __salt__['esxcluster.get_details']()['cluster'], \ __salt__['esxcluster.get_details']()['datacenter'] display_name = '{0}/{1}'.format(datacenter_name, cluster_name) log.info('Running licenses configured for \'%s\'', display_name) log.trace('licenses = %s', licenses) entity = {'type': 'cluster', 'datacenter': datacenter_name, 'cluster': cluster_name} log.trace('entity = %s', entity) comments = [] changes = {} old_licenses = [] new_licenses = [] has_errors = False needs_changes = False try: # Validate licenses log.trace('Validating licenses') schema = LicenseSchema.serialize() try: jsonschema.validate({'licenses': licenses}, schema) except jsonschema.exceptions.ValidationError as exc: raise salt.exceptions.InvalidLicenseError(exc) si = __salt__['vsphere.get_service_instance_via_proxy']() # Retrieve licenses existing_licenses = __salt__['vsphere.list_licenses']( service_instance=si) remaining_licenses = existing_licenses[:] # Cycle through licenses for license_name, license in licenses.items(): # Check if license already exists filtered_licenses = [l for l in existing_licenses if l['key'] == license] # TODO Update license description - not of interest right now if not filtered_licenses: # License doesn't exist - add and assign to cluster needs_changes = True if __opts__['test']: # If it doesn't exist it clearly needs to be assigned as # well so we can stop the check here comments.append('State {0} will add license \'{1}\', ' 'and assign it to cluster \'{2}\'.' ''.format(name, license_name, display_name)) log.info(comments[-1]) continue else: try: existing_license = __salt__['vsphere.add_license']( key=license, description=license_name, service_instance=si) except salt.exceptions.VMwareApiError as ex: comments.append(ex.err_msg) log.error(comments[-1]) has_errors = True continue comments.append('Added license \'{0}\'.' ''.format(license_name)) log.info(comments[-1]) else: # License exists let's check if it's assigned to the cluster comments.append('License \'{0}\' already exists. ' 'Nothing to be done.'.format(license_name)) log.info(comments[-1]) existing_license = filtered_licenses[0] log.trace('Checking licensed entities...') assigned_licenses = __salt__['vsphere.list_assigned_licenses']( entity=entity, entity_display_name=display_name, service_instance=si) # Checking if any of the licenses already assigned have the same # name as the new license; the already assigned license would be # replaced by the new license # # Licenses with different names but matching features would be # replaced as well, but searching for those would be very complex # # the name check if good enough for now already_assigned_license = assigned_licenses[0] if \ assigned_licenses else None if already_assigned_license and \ already_assigned_license['key'] == license: # License is already assigned to entity comments.append('License \'{0}\' already assigned to ' 'cluster \'{1}\'. Nothing to be done.' ''.format(license_name, display_name)) log.info(comments[-1]) continue needs_changes = True # License needs to be assigned to entity if existing_license['capacity'] <= existing_license['used']: # License is already fully used comments.append('Cannot assign license \'{0}\' to cluster ' '\'{1}\'. No free capacity available.' ''.format(license_name, display_name)) log.error(comments[-1]) has_errors = True continue # Assign license if __opts__['test']: comments.append('State {0} will assign license \'{1}\' ' 'to cluster \'{2}\'.'.format( name, license_name, display_name)) log.info(comments[-1]) else: try: __salt__['vsphere.assign_license']( license_key=license, license_name=license_name, entity=entity, entity_display_name=display_name, service_instance=si) except salt.exceptions.VMwareApiError as ex: comments.append(ex.err_msg) log.error(comments[-1]) has_errors = True continue comments.append('Assigned license \'{0}\' to cluster \'{1}\'.' ''.format(license_name, display_name)) log.info(comments[-1]) # Note: Because the already_assigned_license was retrieved # from the assignment license manager it doesn't have a used # value - that's a limitation from VMware. The license would # need to be retrieved again from the license manager to get # the value # Hide license keys assigned_license = __salt__['vsphere.list_assigned_licenses']( entity=entity, entity_display_name=display_name, service_instance=si)[0] assigned_license['key'] = '<hidden>' if already_assigned_license: already_assigned_license['key'] = '<hidden>' if already_assigned_license and \ already_assigned_license['capacity'] == sys.maxsize: already_assigned_license['capacity'] = 'Unlimited' changes[license_name] = {'new': assigned_license, 'old': already_assigned_license} continue __salt__['vsphere.disconnect'](si) ret.update({'result': True if (not needs_changes) else None if __opts__['test'] else False if has_errors else True, 'comment': '\n'.join(comments), 'changes': changes if not __opts__['test'] else {}}) return ret except salt.exceptions.CommandExecutionError as exc: log.exception('Encountered error') if si: __salt__['vsphere.disconnect'](si) ret.update({ 'result': False, 'comment': exc.strerror}) return ret
[ "def", "licenses_configured", "(", "name", ",", "licenses", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "'Default'", "}", "if", "not", "licenses", ...
Configures licenses on the cluster entity Checks if each license exists on the server: - if it doesn't, it creates it Check if license is assigned to the cluster: - if it's not assigned to the cluster: - assign it to the cluster if there is space - error if there's no space - if it's assigned to the cluster nothing needs to be done
[ "Configures", "licenses", "on", "the", "cluster", "entity" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxcluster.py#L353-L537
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
get_system_encoding
def get_system_encoding(): ''' Get system encoding. Most of this code is a part of salt/__init__.py ''' # This is the most trustworthy source of the system encoding, though, if # salt is being imported after being daemonized, this information is lost # and reset to None encoding = None if not sys.platform.startswith('win') and sys.stdin is not None: # On linux we can rely on sys.stdin for the encoding since it # most commonly matches the filesystem encoding. This however # does not apply to windows encoding = sys.stdin.encoding if not encoding: # If the system is properly configured this should return a valid # encoding. MS Windows has problems with this and reports the wrong # encoding import locale try: encoding = locale.getdefaultlocale()[-1] except ValueError: # A bad locale setting was most likely found: # https://github.com/saltstack/salt/issues/26063 pass # This is now garbage collectable del locale if not encoding: # This is most likely ascii which is not the best but we were # unable to find a better encoding. If this fails, we fall all # the way back to ascii encoding = sys.getdefaultencoding() if not encoding: if sys.platform.startswith('darwin'): # Mac OS X uses UTF-8 encoding = 'utf-8' elif sys.platform.startswith('win'): # Windows uses a configurable encoding; on Windows, Python uses the name "mbcs" # to refer to whatever the currently configured encoding is. encoding = 'mbcs' else: # On linux default to ascii as a last resort encoding = 'ascii' return encoding
python
def get_system_encoding(): ''' Get system encoding. Most of this code is a part of salt/__init__.py ''' # This is the most trustworthy source of the system encoding, though, if # salt is being imported after being daemonized, this information is lost # and reset to None encoding = None if not sys.platform.startswith('win') and sys.stdin is not None: # On linux we can rely on sys.stdin for the encoding since it # most commonly matches the filesystem encoding. This however # does not apply to windows encoding = sys.stdin.encoding if not encoding: # If the system is properly configured this should return a valid # encoding. MS Windows has problems with this and reports the wrong # encoding import locale try: encoding = locale.getdefaultlocale()[-1] except ValueError: # A bad locale setting was most likely found: # https://github.com/saltstack/salt/issues/26063 pass # This is now garbage collectable del locale if not encoding: # This is most likely ascii which is not the best but we were # unable to find a better encoding. If this fails, we fall all # the way back to ascii encoding = sys.getdefaultencoding() if not encoding: if sys.platform.startswith('darwin'): # Mac OS X uses UTF-8 encoding = 'utf-8' elif sys.platform.startswith('win'): # Windows uses a configurable encoding; on Windows, Python uses the name "mbcs" # to refer to whatever the currently configured encoding is. encoding = 'mbcs' else: # On linux default to ascii as a last resort encoding = 'ascii' return encoding
[ "def", "get_system_encoding", "(", ")", ":", "# This is the most trustworthy source of the system encoding, though, if", "# salt is being imported after being daemonized, this information is lost", "# and reset to None", "encoding", "=", "None", "if", "not", "sys", ".", "platform", "...
Get system encoding. Most of this code is a part of salt/__init__.py
[ "Get", "system", "encoding", ".", "Most", "of", "this", "code", "is", "a", "part", "of", "salt", "/", "__init__", ".", "py" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L48-L93
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
need_deployment
def need_deployment(): ''' Salt thin needs to be deployed - prep the target directory and emit the delimiter and exit code that signals a required deployment. ''' if os.path.exists(OPTIONS.saltdir): shutil.rmtree(OPTIONS.saltdir) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function try: os.makedirs(OPTIONS.saltdir) finally: os.umask(old_umask) # pylint: disable=blacklisted-function # Verify perms on saltdir if not is_windows(): euid = os.geteuid() dstat = os.stat(OPTIONS.saltdir) if dstat.st_uid != euid: # Attack detected, try again need_deployment() if dstat.st_mode != 16832: # Attack detected need_deployment() # If SUDOing then also give the super user group write permissions sudo_gid = os.environ.get('SUDO_GID') if sudo_gid: try: os.chown(OPTIONS.saltdir, -1, int(sudo_gid)) stt = os.stat(OPTIONS.saltdir) os.chmod(OPTIONS.saltdir, stt.st_mode | stat.S_IWGRP | stat.S_IRGRP | stat.S_IXGRP) except OSError: sys.stdout.write('\n\nUnable to set permissions on thin directory.\nIf sudo_user is set ' 'and is not root, be certain the user is in the same group\nas the login user') sys.exit(1) # Delimiter emitted on stdout *only* to indicate shim message to master. sys.stdout.write("{0}\ndeploy\n".format(OPTIONS.delimiter)) sys.exit(EX_THIN_DEPLOY)
python
def need_deployment(): ''' Salt thin needs to be deployed - prep the target directory and emit the delimiter and exit code that signals a required deployment. ''' if os.path.exists(OPTIONS.saltdir): shutil.rmtree(OPTIONS.saltdir) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function try: os.makedirs(OPTIONS.saltdir) finally: os.umask(old_umask) # pylint: disable=blacklisted-function # Verify perms on saltdir if not is_windows(): euid = os.geteuid() dstat = os.stat(OPTIONS.saltdir) if dstat.st_uid != euid: # Attack detected, try again need_deployment() if dstat.st_mode != 16832: # Attack detected need_deployment() # If SUDOing then also give the super user group write permissions sudo_gid = os.environ.get('SUDO_GID') if sudo_gid: try: os.chown(OPTIONS.saltdir, -1, int(sudo_gid)) stt = os.stat(OPTIONS.saltdir) os.chmod(OPTIONS.saltdir, stt.st_mode | stat.S_IWGRP | stat.S_IRGRP | stat.S_IXGRP) except OSError: sys.stdout.write('\n\nUnable to set permissions on thin directory.\nIf sudo_user is set ' 'and is not root, be certain the user is in the same group\nas the login user') sys.exit(1) # Delimiter emitted on stdout *only* to indicate shim message to master. sys.stdout.write("{0}\ndeploy\n".format(OPTIONS.delimiter)) sys.exit(EX_THIN_DEPLOY)
[ "def", "need_deployment", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "OPTIONS", ".", "saltdir", ")", ":", "shutil", ".", "rmtree", "(", "OPTIONS", ".", "saltdir", ")", "old_umask", "=", "os", ".", "umask", "(", "0o077", ")", "# pylin...
Salt thin needs to be deployed - prep the target directory and emit the delimiter and exit code that signals a required deployment.
[ "Salt", "thin", "needs", "to", "be", "deployed", "-", "prep", "the", "target", "directory", "and", "emit", "the", "delimiter", "and", "exit", "code", "that", "signals", "a", "required", "deployment", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L103-L139
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
get_hash
def get_hash(path, form='sha1', chunk_size=4096): ''' Generate a hash digest string for a file. ''' try: hash_type = getattr(hashlib, form) except AttributeError: raise ValueError('Invalid hash type: {0}'.format(form)) with open(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest()
python
def get_hash(path, form='sha1', chunk_size=4096): ''' Generate a hash digest string for a file. ''' try: hash_type = getattr(hashlib, form) except AttributeError: raise ValueError('Invalid hash type: {0}'.format(form)) with open(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest()
[ "def", "get_hash", "(", "path", ",", "form", "=", "'sha1'", ",", "chunk_size", "=", "4096", ")", ":", "try", ":", "hash_type", "=", "getattr", "(", "hashlib", ",", "form", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "'Invalid hash typ...
Generate a hash digest string for a file.
[ "Generate", "a", "hash", "digest", "string", "for", "a", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L143-L156
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
unpack_thin
def unpack_thin(thin_path): ''' Unpack the Salt thin archive. ''' tfile = tarfile.TarFile.gzopen(thin_path) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function tfile.extractall(path=OPTIONS.saltdir) tfile.close() os.umask(old_umask) # pylint: disable=blacklisted-function try: os.unlink(thin_path) except OSError: pass reset_time(OPTIONS.saltdir)
python
def unpack_thin(thin_path): ''' Unpack the Salt thin archive. ''' tfile = tarfile.TarFile.gzopen(thin_path) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function tfile.extractall(path=OPTIONS.saltdir) tfile.close() os.umask(old_umask) # pylint: disable=blacklisted-function try: os.unlink(thin_path) except OSError: pass reset_time(OPTIONS.saltdir)
[ "def", "unpack_thin", "(", "thin_path", ")", ":", "tfile", "=", "tarfile", ".", "TarFile", ".", "gzopen", "(", "thin_path", ")", "old_umask", "=", "os", ".", "umask", "(", "0o077", ")", "# pylint: disable=blacklisted-function", "tfile", ".", "extractall", "(",...
Unpack the Salt thin archive.
[ "Unpack", "the", "Salt", "thin", "archive", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L159-L172
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
need_ext
def need_ext(): ''' Signal that external modules need to be deployed. ''' sys.stdout.write("{0}\next_mods\n".format(OPTIONS.delimiter)) sys.exit(EX_MOD_DEPLOY)
python
def need_ext(): ''' Signal that external modules need to be deployed. ''' sys.stdout.write("{0}\next_mods\n".format(OPTIONS.delimiter)) sys.exit(EX_MOD_DEPLOY)
[ "def", "need_ext", "(", ")", ":", "sys", ".", "stdout", ".", "write", "(", "\"{0}\\next_mods\\n\"", ".", "format", "(", "OPTIONS", ".", "delimiter", ")", ")", "sys", ".", "exit", "(", "EX_MOD_DEPLOY", ")" ]
Signal that external modules need to be deployed.
[ "Signal", "that", "external", "modules", "need", "to", "be", "deployed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L175-L180
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
unpack_ext
def unpack_ext(ext_path): ''' Unpack the external modules. ''' modcache = os.path.join( OPTIONS.saltdir, 'running_data', 'var', 'cache', 'salt', 'minion', 'extmods') tfile = tarfile.TarFile.gzopen(ext_path) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function tfile.extractall(path=modcache) tfile.close() os.umask(old_umask) # pylint: disable=blacklisted-function os.unlink(ext_path) ver_path = os.path.join(modcache, 'ext_version') ver_dst = os.path.join(OPTIONS.saltdir, 'ext_version') shutil.move(ver_path, ver_dst)
python
def unpack_ext(ext_path): ''' Unpack the external modules. ''' modcache = os.path.join( OPTIONS.saltdir, 'running_data', 'var', 'cache', 'salt', 'minion', 'extmods') tfile = tarfile.TarFile.gzopen(ext_path) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function tfile.extractall(path=modcache) tfile.close() os.umask(old_umask) # pylint: disable=blacklisted-function os.unlink(ext_path) ver_path = os.path.join(modcache, 'ext_version') ver_dst = os.path.join(OPTIONS.saltdir, 'ext_version') shutil.move(ver_path, ver_dst)
[ "def", "unpack_ext", "(", "ext_path", ")", ":", "modcache", "=", "os", ".", "path", ".", "join", "(", "OPTIONS", ".", "saltdir", ",", "'running_data'", ",", "'var'", ",", "'cache'", ",", "'salt'", ",", "'minion'", ",", "'extmods'", ")", "tfile", "=", "...
Unpack the external modules.
[ "Unpack", "the", "external", "modules", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L183-L203
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
reset_time
def reset_time(path='.', amt=None): ''' Reset atime/mtime on all files to prevent systemd swipes only part of the files in the /tmp. ''' if not amt: amt = int(time.time()) for fname in os.listdir(path): fname = os.path.join(path, fname) if os.path.isdir(fname): reset_time(fname, amt=amt) os.utime(fname, (amt, amt,))
python
def reset_time(path='.', amt=None): ''' Reset atime/mtime on all files to prevent systemd swipes only part of the files in the /tmp. ''' if not amt: amt = int(time.time()) for fname in os.listdir(path): fname = os.path.join(path, fname) if os.path.isdir(fname): reset_time(fname, amt=amt) os.utime(fname, (amt, amt,))
[ "def", "reset_time", "(", "path", "=", "'.'", ",", "amt", "=", "None", ")", ":", "if", "not", "amt", ":", "amt", "=", "int", "(", "time", ".", "time", "(", ")", ")", "for", "fname", "in", "os", ".", "listdir", "(", "path", ")", ":", "fname", ...
Reset atime/mtime on all files to prevent systemd swipes only part of the files in the /tmp.
[ "Reset", "atime", "/", "mtime", "on", "all", "files", "to", "prevent", "systemd", "swipes", "only", "part", "of", "the", "files", "in", "the", "/", "tmp", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L206-L216
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
get_executable
def get_executable(): ''' Find executable which matches supported python version in the thin ''' pymap = {} with open(os.path.join(OPTIONS.saltdir, 'supported-versions')) as _fp: for line in _fp.readlines(): ns, v_maj, v_min = line.strip().split(':') pymap[ns] = (int(v_maj), int(v_min)) pycmds = (sys.executable, 'python3', 'python27', 'python2.7', 'python26', 'python2.6', 'python2', 'python') for py_cmd in pycmds: cmd = py_cmd + ' -c "import sys; sys.stdout.write(\'%s:%s\' % (sys.version_info[0], sys.version_info[1]))"' stdout, _ = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate() if sys.version_info[0] == 2 and sys.version_info[1] < 7: stdout = stdout.decode(get_system_encoding(), "replace").strip() else: stdout = stdout.decode(encoding=get_system_encoding(), errors="replace").strip() if not stdout: continue c_vn = tuple([int(x) for x in stdout.split(':')]) for ns in pymap: if c_vn[0] == pymap[ns][0] and c_vn >= pymap[ns] and os.path.exists(os.path.join(OPTIONS.saltdir, ns)): return py_cmd sys.exit(EX_THIN_PYTHON_INVALID)
python
def get_executable(): ''' Find executable which matches supported python version in the thin ''' pymap = {} with open(os.path.join(OPTIONS.saltdir, 'supported-versions')) as _fp: for line in _fp.readlines(): ns, v_maj, v_min = line.strip().split(':') pymap[ns] = (int(v_maj), int(v_min)) pycmds = (sys.executable, 'python3', 'python27', 'python2.7', 'python26', 'python2.6', 'python2', 'python') for py_cmd in pycmds: cmd = py_cmd + ' -c "import sys; sys.stdout.write(\'%s:%s\' % (sys.version_info[0], sys.version_info[1]))"' stdout, _ = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate() if sys.version_info[0] == 2 and sys.version_info[1] < 7: stdout = stdout.decode(get_system_encoding(), "replace").strip() else: stdout = stdout.decode(encoding=get_system_encoding(), errors="replace").strip() if not stdout: continue c_vn = tuple([int(x) for x in stdout.split(':')]) for ns in pymap: if c_vn[0] == pymap[ns][0] and c_vn >= pymap[ns] and os.path.exists(os.path.join(OPTIONS.saltdir, ns)): return py_cmd sys.exit(EX_THIN_PYTHON_INVALID)
[ "def", "get_executable", "(", ")", ":", "pymap", "=", "{", "}", "with", "open", "(", "os", ".", "path", ".", "join", "(", "OPTIONS", ".", "saltdir", ",", "'supported-versions'", ")", ")", "as", "_fp", ":", "for", "line", "in", "_fp", ".", "readlines"...
Find executable which matches supported python version in the thin
[ "Find", "executable", "which", "matches", "supported", "python", "version", "in", "the", "thin" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L219-L244
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
main
def main(argv): # pylint: disable=W0613 ''' Main program body ''' thin_path = os.path.join(OPTIONS.saltdir, THIN_ARCHIVE) if os.path.isfile(thin_path): if OPTIONS.checksum != get_hash(thin_path, OPTIONS.hashfunc): need_deployment() unpack_thin(thin_path) # Salt thin now is available to use else: if not sys.platform.startswith('win'): scpstat = subprocess.Popen(['/bin/sh', '-c', 'command -v scp']).wait() if scpstat != 0: sys.exit(EX_SCP_NOT_FOUND) if os.path.exists(OPTIONS.saltdir) and not os.path.isdir(OPTIONS.saltdir): sys.stderr.write( 'ERROR: salt path "{0}" exists but is' ' not a directory\n'.format(OPTIONS.saltdir) ) sys.exit(EX_CANTCREAT) if not os.path.exists(OPTIONS.saltdir): need_deployment() code_checksum_path = os.path.normpath(os.path.join(OPTIONS.saltdir, 'code-checksum')) if not os.path.exists(code_checksum_path) or not os.path.isfile(code_checksum_path): sys.stderr.write('WARNING: Unable to locate current code checksum: {0}.\n'.format(code_checksum_path)) need_deployment() with open(code_checksum_path, 'r') as vpo: cur_code_cs = vpo.readline().strip() if cur_code_cs != OPTIONS.code_checksum: sys.stderr.write('WARNING: current code checksum {0} is different to {1}.\n'.format(cur_code_cs, OPTIONS.code_checksum)) need_deployment() # Salt thin exists and is up-to-date - fall through and use it salt_call_path = os.path.join(OPTIONS.saltdir, 'salt-call') if not os.path.isfile(salt_call_path): sys.stderr.write('ERROR: thin is missing "{0}"\n'.format(salt_call_path)) need_deployment() with open(os.path.join(OPTIONS.saltdir, 'minion'), 'w') as config: config.write(OPTIONS.config + '\n') if OPTIONS.ext_mods: ext_path = os.path.join(OPTIONS.saltdir, EXT_ARCHIVE) if os.path.exists(ext_path): unpack_ext(ext_path) else: version_path = os.path.join(OPTIONS.saltdir, 'ext_version') if not os.path.exists(version_path) or not os.path.isfile(version_path): need_ext() with open(version_path, 'r') as vpo: cur_version = vpo.readline().strip() if cur_version != OPTIONS.ext_mods: need_ext() # Fix parameter passing issue if len(ARGS) == 1: argv_prepared = ARGS[0].split() else: argv_prepared = ARGS salt_argv = [ get_executable(), salt_call_path, '--retcode-passthrough', '--local', '--metadata', '--out', 'json', '-l', 'quiet', '-c', OPTIONS.saltdir ] try: if argv_prepared[-1].startswith('--no-parse='): salt_argv.append(argv_prepared.pop(-1)) except (IndexError, TypeError): pass salt_argv.append('--') salt_argv.extend(argv_prepared) sys.stderr.write('SALT_ARGV: {0}\n'.format(salt_argv)) # Only emit the delimiter on *both* stdout and stderr when completely successful. # Yes, the flush() is necessary. sys.stdout.write(OPTIONS.delimiter + '\n') sys.stdout.flush() if not OPTIONS.tty: sys.stderr.write(OPTIONS.delimiter + '\n') sys.stderr.flush() if OPTIONS.cmd_umask is not None: old_umask = os.umask(OPTIONS.cmd_umask) # pylint: disable=blacklisted-function if OPTIONS.tty: proc = subprocess.Popen(salt_argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Returns bytes instead of string on python 3 stdout, _ = proc.communicate() sys.stdout.write(stdout.decode(encoding=get_system_encoding(), errors="replace")) sys.stdout.flush() retcode = proc.returncode if OPTIONS.wipe: shutil.rmtree(OPTIONS.saltdir) elif OPTIONS.wipe: retcode = subprocess.call(salt_argv) shutil.rmtree(OPTIONS.saltdir) else: retcode = subprocess.call(salt_argv) if OPTIONS.cmd_umask is not None: os.umask(old_umask) # pylint: disable=blacklisted-function return retcode
python
def main(argv): # pylint: disable=W0613 ''' Main program body ''' thin_path = os.path.join(OPTIONS.saltdir, THIN_ARCHIVE) if os.path.isfile(thin_path): if OPTIONS.checksum != get_hash(thin_path, OPTIONS.hashfunc): need_deployment() unpack_thin(thin_path) # Salt thin now is available to use else: if not sys.platform.startswith('win'): scpstat = subprocess.Popen(['/bin/sh', '-c', 'command -v scp']).wait() if scpstat != 0: sys.exit(EX_SCP_NOT_FOUND) if os.path.exists(OPTIONS.saltdir) and not os.path.isdir(OPTIONS.saltdir): sys.stderr.write( 'ERROR: salt path "{0}" exists but is' ' not a directory\n'.format(OPTIONS.saltdir) ) sys.exit(EX_CANTCREAT) if not os.path.exists(OPTIONS.saltdir): need_deployment() code_checksum_path = os.path.normpath(os.path.join(OPTIONS.saltdir, 'code-checksum')) if not os.path.exists(code_checksum_path) or not os.path.isfile(code_checksum_path): sys.stderr.write('WARNING: Unable to locate current code checksum: {0}.\n'.format(code_checksum_path)) need_deployment() with open(code_checksum_path, 'r') as vpo: cur_code_cs = vpo.readline().strip() if cur_code_cs != OPTIONS.code_checksum: sys.stderr.write('WARNING: current code checksum {0} is different to {1}.\n'.format(cur_code_cs, OPTIONS.code_checksum)) need_deployment() # Salt thin exists and is up-to-date - fall through and use it salt_call_path = os.path.join(OPTIONS.saltdir, 'salt-call') if not os.path.isfile(salt_call_path): sys.stderr.write('ERROR: thin is missing "{0}"\n'.format(salt_call_path)) need_deployment() with open(os.path.join(OPTIONS.saltdir, 'minion'), 'w') as config: config.write(OPTIONS.config + '\n') if OPTIONS.ext_mods: ext_path = os.path.join(OPTIONS.saltdir, EXT_ARCHIVE) if os.path.exists(ext_path): unpack_ext(ext_path) else: version_path = os.path.join(OPTIONS.saltdir, 'ext_version') if not os.path.exists(version_path) or not os.path.isfile(version_path): need_ext() with open(version_path, 'r') as vpo: cur_version = vpo.readline().strip() if cur_version != OPTIONS.ext_mods: need_ext() # Fix parameter passing issue if len(ARGS) == 1: argv_prepared = ARGS[0].split() else: argv_prepared = ARGS salt_argv = [ get_executable(), salt_call_path, '--retcode-passthrough', '--local', '--metadata', '--out', 'json', '-l', 'quiet', '-c', OPTIONS.saltdir ] try: if argv_prepared[-1].startswith('--no-parse='): salt_argv.append(argv_prepared.pop(-1)) except (IndexError, TypeError): pass salt_argv.append('--') salt_argv.extend(argv_prepared) sys.stderr.write('SALT_ARGV: {0}\n'.format(salt_argv)) # Only emit the delimiter on *both* stdout and stderr when completely successful. # Yes, the flush() is necessary. sys.stdout.write(OPTIONS.delimiter + '\n') sys.stdout.flush() if not OPTIONS.tty: sys.stderr.write(OPTIONS.delimiter + '\n') sys.stderr.flush() if OPTIONS.cmd_umask is not None: old_umask = os.umask(OPTIONS.cmd_umask) # pylint: disable=blacklisted-function if OPTIONS.tty: proc = subprocess.Popen(salt_argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Returns bytes instead of string on python 3 stdout, _ = proc.communicate() sys.stdout.write(stdout.decode(encoding=get_system_encoding(), errors="replace")) sys.stdout.flush() retcode = proc.returncode if OPTIONS.wipe: shutil.rmtree(OPTIONS.saltdir) elif OPTIONS.wipe: retcode = subprocess.call(salt_argv) shutil.rmtree(OPTIONS.saltdir) else: retcode = subprocess.call(salt_argv) if OPTIONS.cmd_umask is not None: os.umask(old_umask) # pylint: disable=blacklisted-function return retcode
[ "def", "main", "(", "argv", ")", ":", "# pylint: disable=W0613", "thin_path", "=", "os", ".", "path", ".", "join", "(", "OPTIONS", ".", "saltdir", ",", "THIN_ARCHIVE", ")", "if", "os", ".", "path", ".", "isfile", "(", "thin_path", ")", ":", "if", "OPTI...
Main program body
[ "Main", "program", "body" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L247-L357
train
saltstack/salt
salt/states/btrfs.py
_mount
def _mount(device): ''' Mount the device in a temporary place. ''' dest = tempfile.mkdtemp() res = __states__['mount.mounted'](dest, device=device, fstype='btrfs', opts='subvol=/', persist=False) if not res['result']: log.error('Cannot mount device %s in %s', device, dest) _umount(dest) return None return dest
python
def _mount(device): ''' Mount the device in a temporary place. ''' dest = tempfile.mkdtemp() res = __states__['mount.mounted'](dest, device=device, fstype='btrfs', opts='subvol=/', persist=False) if not res['result']: log.error('Cannot mount device %s in %s', device, dest) _umount(dest) return None return dest
[ "def", "_mount", "(", "device", ")", ":", "dest", "=", "tempfile", ".", "mkdtemp", "(", ")", "res", "=", "__states__", "[", "'mount.mounted'", "]", "(", "dest", ",", "device", "=", "device", ",", "fstype", "=", "'btrfs'", ",", "opts", "=", "'subvol=/'"...
Mount the device in a temporary place.
[ "Mount", "the", "device", "in", "a", "temporary", "place", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/btrfs.py#L44-L55
train
saltstack/salt
salt/states/btrfs.py
_is_default
def _is_default(path, dest, name): ''' Check if the subvolume is the current default. ''' subvol_id = __salt__['btrfs.subvolume_show'](path)[name]['subvolume id'] def_id = __salt__['btrfs.subvolume_get_default'](dest)['id'] return subvol_id == def_id
python
def _is_default(path, dest, name): ''' Check if the subvolume is the current default. ''' subvol_id = __salt__['btrfs.subvolume_show'](path)[name]['subvolume id'] def_id = __salt__['btrfs.subvolume_get_default'](dest)['id'] return subvol_id == def_id
[ "def", "_is_default", "(", "path", ",", "dest", ",", "name", ")", ":", "subvol_id", "=", "__salt__", "[", "'btrfs.subvolume_show'", "]", "(", "path", ")", "[", "name", "]", "[", "'subvolume id'", "]", "def_id", "=", "__salt__", "[", "'btrfs.subvolume_get_def...
Check if the subvolume is the current default.
[ "Check", "if", "the", "subvolume", "is", "the", "current", "default", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/btrfs.py#L66-L72
train
saltstack/salt
salt/states/btrfs.py
_set_default
def _set_default(path, dest, name): ''' Set the subvolume as the current default. ''' subvol_id = __salt__['btrfs.subvolume_show'](path)[name]['subvolume id'] return __salt__['btrfs.subvolume_set_default'](subvol_id, dest)
python
def _set_default(path, dest, name): ''' Set the subvolume as the current default. ''' subvol_id = __salt__['btrfs.subvolume_show'](path)[name]['subvolume id'] return __salt__['btrfs.subvolume_set_default'](subvol_id, dest)
[ "def", "_set_default", "(", "path", ",", "dest", ",", "name", ")", ":", "subvol_id", "=", "__salt__", "[", "'btrfs.subvolume_show'", "]", "(", "path", ")", "[", "name", "]", "[", "'subvolume id'", "]", "return", "__salt__", "[", "'btrfs.subvolume_set_default'"...
Set the subvolume as the current default.
[ "Set", "the", "subvolume", "as", "the", "current", "default", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/btrfs.py#L75-L80
train
saltstack/salt
salt/states/btrfs.py
_is_cow
def _is_cow(path): ''' Check if the subvolume is copy on write ''' dirname = os.path.dirname(path) return 'C' not in __salt__['file.lsattr'](dirname)[path]
python
def _is_cow(path): ''' Check if the subvolume is copy on write ''' dirname = os.path.dirname(path) return 'C' not in __salt__['file.lsattr'](dirname)[path]
[ "def", "_is_cow", "(", "path", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "return", "'C'", "not", "in", "__salt__", "[", "'file.lsattr'", "]", "(", "dirname", ")", "[", "path", "]" ]
Check if the subvolume is copy on write
[ "Check", "if", "the", "subvolume", "is", "copy", "on", "write" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/btrfs.py#L83-L88
train
saltstack/salt
salt/states/btrfs.py
__mount_device
def __mount_device(action): ''' Small decorator to makes sure that the mount and umount happends in a transactional way. ''' @functools.wraps(action) def wrapper(*args, **kwargs): name = kwargs['name'] device = kwargs['device'] ret = { 'name': name, 'result': False, 'changes': {}, 'comment': ['Some error happends during the operation.'], } try: dest = _mount(device) if not dest: msg = 'Device {} cannot be mounted'.format(device) ret['comment'].append(msg) kwargs['__dest'] = dest ret = action(*args, **kwargs) except Exception as e: log.exception('Encountered error mounting %s', device) ret['comment'].append(six.text_type(e)) finally: _umount(dest) return ret return wrapper
python
def __mount_device(action): ''' Small decorator to makes sure that the mount and umount happends in a transactional way. ''' @functools.wraps(action) def wrapper(*args, **kwargs): name = kwargs['name'] device = kwargs['device'] ret = { 'name': name, 'result': False, 'changes': {}, 'comment': ['Some error happends during the operation.'], } try: dest = _mount(device) if not dest: msg = 'Device {} cannot be mounted'.format(device) ret['comment'].append(msg) kwargs['__dest'] = dest ret = action(*args, **kwargs) except Exception as e: log.exception('Encountered error mounting %s', device) ret['comment'].append(six.text_type(e)) finally: _umount(dest) return ret return wrapper
[ "def", "__mount_device", "(", "action", ")", ":", "@", "functools", ".", "wraps", "(", "action", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", "[", "'name'", "]", "device", "=", "kwargs", "[", "'...
Small decorator to makes sure that the mount and umount happends in a transactional way.
[ "Small", "decorator", "to", "makes", "sure", "that", "the", "mount", "and", "umount", "happends", "in", "a", "transactional", "way", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/btrfs.py#L98-L127
train
saltstack/salt
salt/states/btrfs.py
subvolume_created
def subvolume_created(name, device, qgroupids=None, set_default=False, copy_on_write=True, force_set_default=True, __dest=None): ''' Makes sure that a btrfs subvolume is present. name Name of the subvolume to add device Device where to create the subvolume qgroupids Add the newly created subcolume to a qgroup. This parameter is a list set_default If True, this new subvolume will be set as default when mounted, unless subvol option in mount is used copy_on_write If false, set the subvolume with chattr +C force_set_default If false and the subvolume is already present, it will not force it as default if ``set_default`` is True ''' ret = { 'name': name, 'result': False, 'changes': {}, 'comment': [], } path = os.path.join(__dest, name) exists = __salt__['btrfs.subvolume_exists'](path) if exists: ret['comment'].append('Subvolume {} already present'.format(name)) # Resolve first the test case. The check is not complete, but at # least we will report if a subvolume needs to be created. Can # happend that the subvolume is there, but we also need to set it # as default, or persist in fstab. if __opts__['test']: ret['result'] = None if not exists: ret['comment'].append('Subvolume {} will be created'.format(name)) return ret if not exists: # Create the directories where the subvolume lives _path = os.path.dirname(path) res = __states__['file.directory'](_path, makedirs=True) if not res['result']: ret['comment'].append('Error creating {} directory'.format(_path)) return ret try: __salt__['btrfs.subvolume_create'](name, dest=__dest, qgroupids=qgroupids) except CommandExecutionError: ret['comment'].append('Error creating subvolume {}'.format(name)) return ret ret['changes'][name] = 'Created subvolume {}'.format(name) # If the volume was already present, we can opt-out the check for # default subvolume. if (not exists or (exists and force_set_default)) and \ set_default and not _is_default(path, __dest, name): ret['changes'][name + '_default'] = _set_default(path, __dest, name) if not copy_on_write and _is_cow(path): ret['changes'][name + '_no_cow'] = _unset_cow(path) ret['result'] = True return ret
python
def subvolume_created(name, device, qgroupids=None, set_default=False, copy_on_write=True, force_set_default=True, __dest=None): ''' Makes sure that a btrfs subvolume is present. name Name of the subvolume to add device Device where to create the subvolume qgroupids Add the newly created subcolume to a qgroup. This parameter is a list set_default If True, this new subvolume will be set as default when mounted, unless subvol option in mount is used copy_on_write If false, set the subvolume with chattr +C force_set_default If false and the subvolume is already present, it will not force it as default if ``set_default`` is True ''' ret = { 'name': name, 'result': False, 'changes': {}, 'comment': [], } path = os.path.join(__dest, name) exists = __salt__['btrfs.subvolume_exists'](path) if exists: ret['comment'].append('Subvolume {} already present'.format(name)) # Resolve first the test case. The check is not complete, but at # least we will report if a subvolume needs to be created. Can # happend that the subvolume is there, but we also need to set it # as default, or persist in fstab. if __opts__['test']: ret['result'] = None if not exists: ret['comment'].append('Subvolume {} will be created'.format(name)) return ret if not exists: # Create the directories where the subvolume lives _path = os.path.dirname(path) res = __states__['file.directory'](_path, makedirs=True) if not res['result']: ret['comment'].append('Error creating {} directory'.format(_path)) return ret try: __salt__['btrfs.subvolume_create'](name, dest=__dest, qgroupids=qgroupids) except CommandExecutionError: ret['comment'].append('Error creating subvolume {}'.format(name)) return ret ret['changes'][name] = 'Created subvolume {}'.format(name) # If the volume was already present, we can opt-out the check for # default subvolume. if (not exists or (exists and force_set_default)) and \ set_default and not _is_default(path, __dest, name): ret['changes'][name + '_default'] = _set_default(path, __dest, name) if not copy_on_write and _is_cow(path): ret['changes'][name + '_no_cow'] = _unset_cow(path) ret['result'] = True return ret
[ "def", "subvolume_created", "(", "name", ",", "device", ",", "qgroupids", "=", "None", ",", "set_default", "=", "False", ",", "copy_on_write", "=", "True", ",", "force_set_default", "=", "True", ",", "__dest", "=", "None", ")", ":", "ret", "=", "{", "'na...
Makes sure that a btrfs subvolume is present. name Name of the subvolume to add device Device where to create the subvolume qgroupids Add the newly created subcolume to a qgroup. This parameter is a list set_default If True, this new subvolume will be set as default when mounted, unless subvol option in mount is used copy_on_write If false, set the subvolume with chattr +C force_set_default If false and the subvolume is already present, it will not force it as default if ``set_default`` is True
[ "Makes", "sure", "that", "a", "btrfs", "subvolume", "is", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/btrfs.py#L131-L208
train
saltstack/salt
salt/states/btrfs.py
subvolume_deleted
def subvolume_deleted(name, device, commit=False, __dest=None): ''' Makes sure that a btrfs subvolume is removed. name Name of the subvolume to remove device Device where to remove the subvolume commit Wait until the transaction is over ''' ret = { 'name': name, 'result': False, 'changes': {}, 'comment': [], } path = os.path.join(__dest, name) exists = __salt__['btrfs.subvolume_exists'](path) if not exists: ret['comment'].append('Subvolume {} already missing'.format(name)) if __opts__['test']: ret['result'] = None if exists: ret['comment'].append('Subvolume {} will be removed'.format(name)) return ret # If commit is set, we wait until all is over commit = 'after' if commit else None if not exists: try: __salt__['btrfs.subvolume_delete'](path, commit=commit) except CommandExecutionError: ret['comment'].append('Error removing subvolume {}'.format(name)) return ret ret['changes'][name] = 'Removed subvolume {}'.format(name) ret['result'] = True return ret
python
def subvolume_deleted(name, device, commit=False, __dest=None): ''' Makes sure that a btrfs subvolume is removed. name Name of the subvolume to remove device Device where to remove the subvolume commit Wait until the transaction is over ''' ret = { 'name': name, 'result': False, 'changes': {}, 'comment': [], } path = os.path.join(__dest, name) exists = __salt__['btrfs.subvolume_exists'](path) if not exists: ret['comment'].append('Subvolume {} already missing'.format(name)) if __opts__['test']: ret['result'] = None if exists: ret['comment'].append('Subvolume {} will be removed'.format(name)) return ret # If commit is set, we wait until all is over commit = 'after' if commit else None if not exists: try: __salt__['btrfs.subvolume_delete'](path, commit=commit) except CommandExecutionError: ret['comment'].append('Error removing subvolume {}'.format(name)) return ret ret['changes'][name] = 'Removed subvolume {}'.format(name) ret['result'] = True return ret
[ "def", "subvolume_deleted", "(", "name", ",", "device", ",", "commit", "=", "False", ",", "__dest", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", ...
Makes sure that a btrfs subvolume is removed. name Name of the subvolume to remove device Device where to remove the subvolume commit Wait until the transaction is over
[ "Makes", "sure", "that", "a", "btrfs", "subvolume", "is", "removed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/btrfs.py#L212-L258
train
saltstack/salt
salt/pillar/cmd_yaml.py
ext_pillar
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 command): ''' Execute a command and read the output as YAML ''' try: command = command.replace('%s', minion_id) output = __salt__['cmd.run_stdout'](command, python_shell=True) return salt.utils.yaml.safe_load(output) except Exception: log.critical( 'YAML data from \'%s\' failed to parse. Command output:\n%s', command, output ) return {}
python
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 command): ''' Execute a command and read the output as YAML ''' try: command = command.replace('%s', minion_id) output = __salt__['cmd.run_stdout'](command, python_shell=True) return salt.utils.yaml.safe_load(output) except Exception: log.critical( 'YAML data from \'%s\' failed to parse. Command output:\n%s', command, output ) return {}
[ "def", "ext_pillar", "(", "minion_id", ",", "# pylint: disable=W0613", "pillar", ",", "# pylint: disable=W0613", "command", ")", ":", "try", ":", "command", "=", "command", ".", "replace", "(", "'%s'", ",", "minion_id", ")", "output", "=", "__salt__", "[", "'c...
Execute a command and read the output as YAML
[ "Execute", "a", "command", "and", "read", "the", "output", "as", "YAML" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/cmd_yaml.py#L20-L35
train
saltstack/salt
salt/states/azurearm_dns.py
zone_present
def zone_present(name, resource_group, etag=None, if_match=None, if_none_match=None, registration_virtual_networks=None, resolution_virtual_networks=None, tags=None, zone_type='Public', connection_auth=None, **kwargs): ''' .. versionadded:: Fluorine Ensure a DNS zone exists. :param name: Name of the DNS zone (without a terminating dot). :param resource_group: The resource group assigned to the DNS zone. :param etag: The etag of the zone. `Etags <https://docs.microsoft.com/en-us/azure/dns/dns-zones-records#etags>`_ are used to handle concurrent changes to the same resource safely. :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwritting any concurrent changes. :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating an existing zone. Other values will be ignored. :param registration_virtual_networks: A list of references to virtual networks that register hostnames in this DNS zone. This is only when zone_type is Private. (requires `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1) :param resolution_virtual_networks: A list of references to virtual networks that resolve records in this DNS zone. This is only when zone_type is Private. (requires `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1) :param tags: A dictionary of strings can be passed as tag metadata to the DNS zone object. :param zone_type: The type of this DNS zone (Public or Private). Possible values include: 'Public', 'Private'. Default value: 'Public' (requires `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1) :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure DNS zone exists: azurearm_dns.zone_present: - name: contoso.com - resource_group: my_rg - zone_type: Private - registration_virtual_networks: - /subscriptions/{{ sub }}/resourceGroups/my_rg/providers/Microsoft.Network/virtualNetworks/test_vnet - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret zone = __salt__['azurearm_dns.zone_get'](name, resource_group, azurearm_log_level='info', **connection_auth) if 'error' not in zone: tag_changes = __utils__['dictdiffer.deep_diff'](zone.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # The zone_type parameter is only accessible in azure-mgmt-dns >=2.0.0rc1 if zone.get('zone_type'): if zone.get('zone_type').lower() != zone_type.lower(): ret['changes']['zone_type'] = { 'old': zone['zone_type'], 'new': zone_type } if zone_type.lower() == 'private': # The registration_virtual_networks parameter is only accessible in azure-mgmt-dns >=2.0.0rc1 if registration_virtual_networks and not isinstance(registration_virtual_networks, list): ret['comment'] = 'registration_virtual_networks must be supplied as a list of VNET ID paths!' return ret reg_vnets = zone.get('registration_virtual_networks', []) remote_reg_vnets = sorted([vnet['id'].lower() for vnet in reg_vnets if 'id' in vnet]) local_reg_vnets = sorted([vnet.lower() for vnet in registration_virtual_networks or []]) if local_reg_vnets != remote_reg_vnets: ret['changes']['registration_virtual_networks'] = { 'old': remote_reg_vnets, 'new': local_reg_vnets } # The resolution_virtual_networks parameter is only accessible in azure-mgmt-dns >=2.0.0rc1 if resolution_virtual_networks and not isinstance(resolution_virtual_networks, list): ret['comment'] = 'resolution_virtual_networks must be supplied as a list of VNET ID paths!' return ret res_vnets = zone.get('resolution_virtual_networks', []) remote_res_vnets = sorted([vnet['id'].lower() for vnet in res_vnets if 'id' in vnet]) local_res_vnets = sorted([vnet.lower() for vnet in resolution_virtual_networks or []]) if local_res_vnets != remote_res_vnets: ret['changes']['resolution_virtual_networks'] = { 'old': remote_res_vnets, 'new': local_res_vnets } if not ret['changes']: ret['result'] = True ret['comment'] = 'DNS zone {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'DNS zone {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'etag': etag, 'registration_virtual_networks': registration_virtual_networks, 'resolution_virtual_networks': resolution_virtual_networks, 'tags': tags, 'zone_type': zone_type, } } if __opts__['test']: ret['comment'] = 'DNS zone {0} would be created.'.format(name) ret['result'] = None return ret zone_kwargs = kwargs.copy() zone_kwargs.update(connection_auth) zone = __salt__['azurearm_dns.zone_create_or_update']( name=name, resource_group=resource_group, etag=etag, if_match=if_match, if_none_match=if_none_match, registration_virtual_networks=registration_virtual_networks, resolution_virtual_networks=resolution_virtual_networks, tags=tags, zone_type=zone_type, **zone_kwargs ) if 'error' not in zone: ret['result'] = True ret['comment'] = 'DNS zone {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create DNS zone {0}! ({1})'.format(name, zone.get('error')) return ret
python
def zone_present(name, resource_group, etag=None, if_match=None, if_none_match=None, registration_virtual_networks=None, resolution_virtual_networks=None, tags=None, zone_type='Public', connection_auth=None, **kwargs): ''' .. versionadded:: Fluorine Ensure a DNS zone exists. :param name: Name of the DNS zone (without a terminating dot). :param resource_group: The resource group assigned to the DNS zone. :param etag: The etag of the zone. `Etags <https://docs.microsoft.com/en-us/azure/dns/dns-zones-records#etags>`_ are used to handle concurrent changes to the same resource safely. :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwritting any concurrent changes. :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating an existing zone. Other values will be ignored. :param registration_virtual_networks: A list of references to virtual networks that register hostnames in this DNS zone. This is only when zone_type is Private. (requires `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1) :param resolution_virtual_networks: A list of references to virtual networks that resolve records in this DNS zone. This is only when zone_type is Private. (requires `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1) :param tags: A dictionary of strings can be passed as tag metadata to the DNS zone object. :param zone_type: The type of this DNS zone (Public or Private). Possible values include: 'Public', 'Private'. Default value: 'Public' (requires `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1) :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure DNS zone exists: azurearm_dns.zone_present: - name: contoso.com - resource_group: my_rg - zone_type: Private - registration_virtual_networks: - /subscriptions/{{ sub }}/resourceGroups/my_rg/providers/Microsoft.Network/virtualNetworks/test_vnet - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret zone = __salt__['azurearm_dns.zone_get'](name, resource_group, azurearm_log_level='info', **connection_auth) if 'error' not in zone: tag_changes = __utils__['dictdiffer.deep_diff'](zone.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # The zone_type parameter is only accessible in azure-mgmt-dns >=2.0.0rc1 if zone.get('zone_type'): if zone.get('zone_type').lower() != zone_type.lower(): ret['changes']['zone_type'] = { 'old': zone['zone_type'], 'new': zone_type } if zone_type.lower() == 'private': # The registration_virtual_networks parameter is only accessible in azure-mgmt-dns >=2.0.0rc1 if registration_virtual_networks and not isinstance(registration_virtual_networks, list): ret['comment'] = 'registration_virtual_networks must be supplied as a list of VNET ID paths!' return ret reg_vnets = zone.get('registration_virtual_networks', []) remote_reg_vnets = sorted([vnet['id'].lower() for vnet in reg_vnets if 'id' in vnet]) local_reg_vnets = sorted([vnet.lower() for vnet in registration_virtual_networks or []]) if local_reg_vnets != remote_reg_vnets: ret['changes']['registration_virtual_networks'] = { 'old': remote_reg_vnets, 'new': local_reg_vnets } # The resolution_virtual_networks parameter is only accessible in azure-mgmt-dns >=2.0.0rc1 if resolution_virtual_networks and not isinstance(resolution_virtual_networks, list): ret['comment'] = 'resolution_virtual_networks must be supplied as a list of VNET ID paths!' return ret res_vnets = zone.get('resolution_virtual_networks', []) remote_res_vnets = sorted([vnet['id'].lower() for vnet in res_vnets if 'id' in vnet]) local_res_vnets = sorted([vnet.lower() for vnet in resolution_virtual_networks or []]) if local_res_vnets != remote_res_vnets: ret['changes']['resolution_virtual_networks'] = { 'old': remote_res_vnets, 'new': local_res_vnets } if not ret['changes']: ret['result'] = True ret['comment'] = 'DNS zone {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'DNS zone {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'etag': etag, 'registration_virtual_networks': registration_virtual_networks, 'resolution_virtual_networks': resolution_virtual_networks, 'tags': tags, 'zone_type': zone_type, } } if __opts__['test']: ret['comment'] = 'DNS zone {0} would be created.'.format(name) ret['result'] = None return ret zone_kwargs = kwargs.copy() zone_kwargs.update(connection_auth) zone = __salt__['azurearm_dns.zone_create_or_update']( name=name, resource_group=resource_group, etag=etag, if_match=if_match, if_none_match=if_none_match, registration_virtual_networks=registration_virtual_networks, resolution_virtual_networks=resolution_virtual_networks, tags=tags, zone_type=zone_type, **zone_kwargs ) if 'error' not in zone: ret['result'] = True ret['comment'] = 'DNS zone {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create DNS zone {0}! ({1})'.format(name, zone.get('error')) return ret
[ "def", "zone_present", "(", "name", ",", "resource_group", ",", "etag", "=", "None", ",", "if_match", "=", "None", ",", "if_none_match", "=", "None", ",", "registration_virtual_networks", "=", "None", ",", "resolution_virtual_networks", "=", "None", ",", "tags",...
.. versionadded:: Fluorine Ensure a DNS zone exists. :param name: Name of the DNS zone (without a terminating dot). :param resource_group: The resource group assigned to the DNS zone. :param etag: The etag of the zone. `Etags <https://docs.microsoft.com/en-us/azure/dns/dns-zones-records#etags>`_ are used to handle concurrent changes to the same resource safely. :param if_match: The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally overwritting any concurrent changes. :param if_none_match: Set to '*' to allow a new DNS zone to be created, but to prevent updating an existing zone. Other values will be ignored. :param registration_virtual_networks: A list of references to virtual networks that register hostnames in this DNS zone. This is only when zone_type is Private. (requires `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1) :param resolution_virtual_networks: A list of references to virtual networks that resolve records in this DNS zone. This is only when zone_type is Private. (requires `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1) :param tags: A dictionary of strings can be passed as tag metadata to the DNS zone object. :param zone_type: The type of this DNS zone (Public or Private). Possible values include: 'Public', 'Private'. Default value: 'Public' (requires `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1) :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure DNS zone exists: azurearm_dns.zone_present: - name: contoso.com - resource_group: my_rg - zone_type: Private - registration_virtual_networks: - /subscriptions/{{ sub }}/resourceGroups/my_rg/providers/Microsoft.Network/virtualNetworks/test_vnet - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }}
[ "..", "versionadded", "::", "Fluorine" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_dns.py#L131-L297
train
saltstack/salt
salt/states/azurearm_dns.py
zone_absent
def zone_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: Fluorine Ensure a DNS zone does not exist in the resource group. :param name: Name of the DNS zone. :param resource_group: The resource group assigned to the DNS zone. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret zone = __salt__['azurearm_dns.zone_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in zone: ret['result'] = True ret['comment'] = 'DNS zone {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'DNS zone {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': zone, 'new': {}, } return ret deleted = __salt__['azurearm_dns.zone_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'DNS zone {0} has been deleted.'.format(name) ret['changes'] = { 'old': zone, 'new': {} } return ret ret['comment'] = 'Failed to delete DNS zone {0}!'.format(name) return ret
python
def zone_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: Fluorine Ensure a DNS zone does not exist in the resource group. :param name: Name of the DNS zone. :param resource_group: The resource group assigned to the DNS zone. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret zone = __salt__['azurearm_dns.zone_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in zone: ret['result'] = True ret['comment'] = 'DNS zone {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'DNS zone {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': zone, 'new': {}, } return ret deleted = __salt__['azurearm_dns.zone_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'DNS zone {0} has been deleted.'.format(name) ret['changes'] = { 'old': zone, 'new': {} } return ret ret['comment'] = 'Failed to delete DNS zone {0}!'.format(name) return ret
[ "def", "zone_absent", "(", "name", ",", "resource_group", ",", "connection_auth", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "if", "...
.. versionadded:: Fluorine Ensure a DNS zone does not exist in the resource group. :param name: Name of the DNS zone. :param resource_group: The resource group assigned to the DNS zone. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API.
[ "..", "versionadded", "::", "Fluorine" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_dns.py#L300-L360
train
saltstack/salt
salt/states/azurearm_dns.py
record_set_present
def record_set_present(name, zone_name, resource_group, record_type, if_match=None, if_none_match=None, etag=None, metadata=None, ttl=None, arecords=None, aaaa_records=None, mx_records=None, ns_records=None, ptr_records=None, srv_records=None, txt_records=None, cname_record=None, soa_record=None, caa_records=None, connection_auth=None, **kwargs): ''' .. versionadded:: Fluorine Ensure a record set exists in a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: Name of the DNS zone (without a terminating dot). :param resource_group: The resource group assigned to the DNS zone. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwritting any concurrent changes. :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will be ignored. :param etag: The etag of the record set. `Etags <https://docs.microsoft.com/en-us/azure/dns/dns-zones-records#etags>`_ are used to handle concurrent changes to the same resource safely. :param metadata: A dictionary of strings can be passed as tag metadata to the record set object. :param ttl: The TTL (time-to-live) of the records in the record set. Required when specifying record information. :param arecords: The list of A records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.arecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param aaaa_records: The list of AAAA records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.aaaarecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param mx_records: The list of MX records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.mxrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param ns_records: The list of NS records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.nsrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param ptr_records: The list of PTR records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.ptrrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param srv_records: The list of SRV records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.srvrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param txt_records: The list of TXT records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.txtrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param cname_record: The CNAME record in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.cnamerecord?view=azure-python>`_ to create a dictionary representing the record object. :param soa_record: The SOA record in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.soarecord?view=azure-python>`_ to create a dictionary representing the record object. :param caa_records: The list of CAA records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.caarecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure record set exists: azurearm_dns.record_set_present: - name: web - zone_name: contoso.com - resource_group: my_rg - record_type: A - ttl: 300 - arecords: - ipv4_address: 10.0.0.1 - metadata: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } record_vars = [ 'arecords', 'aaaa_records', 'mx_records', 'ns_records', 'ptr_records', 'srv_records', 'txt_records', 'cname_record', 'soa_record', 'caa_records' ] if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rec_set = __salt__['azurearm_dns.record_set_get']( name, zone_name, resource_group, record_type, azurearm_log_level='info', **connection_auth ) if 'error' not in rec_set: metadata_changes = __utils__['dictdiffer.deep_diff'](rec_set.get('metadata', {}), metadata or {}) if metadata_changes: ret['changes']['metadata'] = metadata_changes for record_str in record_vars: # pylint: disable=eval-used record = eval(record_str) if record: if not ttl: ret['comment'] = 'TTL is required when specifying record information!' return ret if not rec_set.get(record_str): ret['changes'] = {'new': {record_str: record}} continue if record_str[-1] != 's': if not isinstance(record, dict): ret['comment'] = '{0} record information must be specified as a dictionary!'.format(record_str) return ret for k, v in record.items(): if v != rec_set[record_str].get(k): ret['changes'] = {'new': {record_str: record}} elif record_str[-1] == 's': if not isinstance(record, list): ret['comment'] = '{0} record information must be specified as a list of dictionaries!'.format( record_str ) return ret local, remote = [sorted(config) for config in (record, rec_set[record_str])] for idx in six_range(0, len(local)): for key in local[idx]: local_val = local[idx][key] remote_val = remote[idx].get(key) if isinstance(local_val, six.string_types): local_val = local_val.lower() if isinstance(remote_val, six.string_types): remote_val = remote_val.lower() if local_val != remote_val: ret['changes'] = {'new': {record_str: record}} if not ret['changes']: ret['result'] = True ret['comment'] = 'Record set {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Record set {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'zone_name': zone_name, 'resource_group': resource_group, 'record_type': record_type, 'etag': etag, 'metadata': metadata, 'ttl': ttl, } } for record in record_vars: # pylint: disable=eval-used if eval(record): # pylint: disable=eval-used ret['changes']['new'][record] = eval(record) if __opts__['test']: ret['comment'] = 'Record set {0} would be created.'.format(name) ret['result'] = None return ret rec_set_kwargs = kwargs.copy() rec_set_kwargs.update(connection_auth) rec_set = __salt__['azurearm_dns.record_set_create_or_update']( name=name, zone_name=zone_name, resource_group=resource_group, record_type=record_type, if_match=if_match, if_none_match=if_none_match, etag=etag, ttl=ttl, metadata=metadata, arecords=arecords, aaaa_records=aaaa_records, mx_records=mx_records, ns_records=ns_records, ptr_records=ptr_records, srv_records=srv_records, txt_records=txt_records, cname_record=cname_record, soa_record=soa_record, caa_records=caa_records, **rec_set_kwargs ) if 'error' not in rec_set: ret['result'] = True ret['comment'] = 'Record set {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create record set {0}! ({1})'.format(name, rec_set.get('error')) return ret
python
def record_set_present(name, zone_name, resource_group, record_type, if_match=None, if_none_match=None, etag=None, metadata=None, ttl=None, arecords=None, aaaa_records=None, mx_records=None, ns_records=None, ptr_records=None, srv_records=None, txt_records=None, cname_record=None, soa_record=None, caa_records=None, connection_auth=None, **kwargs): ''' .. versionadded:: Fluorine Ensure a record set exists in a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: Name of the DNS zone (without a terminating dot). :param resource_group: The resource group assigned to the DNS zone. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwritting any concurrent changes. :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will be ignored. :param etag: The etag of the record set. `Etags <https://docs.microsoft.com/en-us/azure/dns/dns-zones-records#etags>`_ are used to handle concurrent changes to the same resource safely. :param metadata: A dictionary of strings can be passed as tag metadata to the record set object. :param ttl: The TTL (time-to-live) of the records in the record set. Required when specifying record information. :param arecords: The list of A records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.arecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param aaaa_records: The list of AAAA records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.aaaarecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param mx_records: The list of MX records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.mxrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param ns_records: The list of NS records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.nsrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param ptr_records: The list of PTR records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.ptrrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param srv_records: The list of SRV records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.srvrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param txt_records: The list of TXT records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.txtrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param cname_record: The CNAME record in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.cnamerecord?view=azure-python>`_ to create a dictionary representing the record object. :param soa_record: The SOA record in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.soarecord?view=azure-python>`_ to create a dictionary representing the record object. :param caa_records: The list of CAA records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.caarecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure record set exists: azurearm_dns.record_set_present: - name: web - zone_name: contoso.com - resource_group: my_rg - record_type: A - ttl: 300 - arecords: - ipv4_address: 10.0.0.1 - metadata: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } record_vars = [ 'arecords', 'aaaa_records', 'mx_records', 'ns_records', 'ptr_records', 'srv_records', 'txt_records', 'cname_record', 'soa_record', 'caa_records' ] if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rec_set = __salt__['azurearm_dns.record_set_get']( name, zone_name, resource_group, record_type, azurearm_log_level='info', **connection_auth ) if 'error' not in rec_set: metadata_changes = __utils__['dictdiffer.deep_diff'](rec_set.get('metadata', {}), metadata or {}) if metadata_changes: ret['changes']['metadata'] = metadata_changes for record_str in record_vars: # pylint: disable=eval-used record = eval(record_str) if record: if not ttl: ret['comment'] = 'TTL is required when specifying record information!' return ret if not rec_set.get(record_str): ret['changes'] = {'new': {record_str: record}} continue if record_str[-1] != 's': if not isinstance(record, dict): ret['comment'] = '{0} record information must be specified as a dictionary!'.format(record_str) return ret for k, v in record.items(): if v != rec_set[record_str].get(k): ret['changes'] = {'new': {record_str: record}} elif record_str[-1] == 's': if not isinstance(record, list): ret['comment'] = '{0} record information must be specified as a list of dictionaries!'.format( record_str ) return ret local, remote = [sorted(config) for config in (record, rec_set[record_str])] for idx in six_range(0, len(local)): for key in local[idx]: local_val = local[idx][key] remote_val = remote[idx].get(key) if isinstance(local_val, six.string_types): local_val = local_val.lower() if isinstance(remote_val, six.string_types): remote_val = remote_val.lower() if local_val != remote_val: ret['changes'] = {'new': {record_str: record}} if not ret['changes']: ret['result'] = True ret['comment'] = 'Record set {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Record set {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'zone_name': zone_name, 'resource_group': resource_group, 'record_type': record_type, 'etag': etag, 'metadata': metadata, 'ttl': ttl, } } for record in record_vars: # pylint: disable=eval-used if eval(record): # pylint: disable=eval-used ret['changes']['new'][record] = eval(record) if __opts__['test']: ret['comment'] = 'Record set {0} would be created.'.format(name) ret['result'] = None return ret rec_set_kwargs = kwargs.copy() rec_set_kwargs.update(connection_auth) rec_set = __salt__['azurearm_dns.record_set_create_or_update']( name=name, zone_name=zone_name, resource_group=resource_group, record_type=record_type, if_match=if_match, if_none_match=if_none_match, etag=etag, ttl=ttl, metadata=metadata, arecords=arecords, aaaa_records=aaaa_records, mx_records=mx_records, ns_records=ns_records, ptr_records=ptr_records, srv_records=srv_records, txt_records=txt_records, cname_record=cname_record, soa_record=soa_record, caa_records=caa_records, **rec_set_kwargs ) if 'error' not in rec_set: ret['result'] = True ret['comment'] = 'Record set {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create record set {0}! ({1})'.format(name, rec_set.get('error')) return ret
[ "def", "record_set_present", "(", "name", ",", "zone_name", ",", "resource_group", ",", "record_type", ",", "if_match", "=", "None", ",", "if_none_match", "=", "None", ",", "etag", "=", "None", ",", "metadata", "=", "None", ",", "ttl", "=", "None", ",", ...
.. versionadded:: Fluorine Ensure a record set exists in a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: Name of the DNS zone (without a terminating dot). :param resource_group: The resource group assigned to the DNS zone. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param if_match: The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwritting any concurrent changes. :param if_none_match: Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will be ignored. :param etag: The etag of the record set. `Etags <https://docs.microsoft.com/en-us/azure/dns/dns-zones-records#etags>`_ are used to handle concurrent changes to the same resource safely. :param metadata: A dictionary of strings can be passed as tag metadata to the record set object. :param ttl: The TTL (time-to-live) of the records in the record set. Required when specifying record information. :param arecords: The list of A records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.arecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param aaaa_records: The list of AAAA records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.aaaarecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param mx_records: The list of MX records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.mxrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param ns_records: The list of NS records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.nsrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param ptr_records: The list of PTR records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.ptrrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param srv_records: The list of SRV records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.srvrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param txt_records: The list of TXT records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.txtrecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param cname_record: The CNAME record in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.cnamerecord?view=azure-python>`_ to create a dictionary representing the record object. :param soa_record: The SOA record in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.soarecord?view=azure-python>`_ to create a dictionary representing the record object. :param caa_records: The list of CAA records in the record set. View the `Azure SDK documentation <https://docs.microsoft.com/en-us/python/api/azure.mgmt.dns.models.caarecord?view=azure-python>`_ to create a list of dictionaries representing the record objects. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure record set exists: azurearm_dns.record_set_present: - name: web - zone_name: contoso.com - resource_group: my_rg - record_type: A - ttl: 300 - arecords: - ipv4_address: 10.0.0.1 - metadata: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }}
[ "..", "versionadded", "::", "Fluorine" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_dns.py#L363-L616
train
saltstack/salt
salt/states/azurearm_dns.py
record_set_absent
def record_set_absent(name, zone_name, resource_group, connection_auth=None): ''' .. versionadded:: Fluorine Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name of the DNS zone. :param resource_group: The resource group assigned to the DNS zone. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rec_set = __salt__['azurearm_dns.record_set_get']( name, zone_name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rec_set: ret['result'] = True ret['comment'] = 'Record set {0} was not found in zone {1}.'.format(name, zone_name) return ret elif __opts__['test']: ret['comment'] = 'Record set {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rec_set, 'new': {}, } return ret deleted = __salt__['azurearm_dns.record_set_delete'](name, zone_name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Record set {0} has been deleted.'.format(name) ret['changes'] = { 'old': rec_set, 'new': {} } return ret ret['comment'] = 'Failed to delete record set {0}!'.format(name) return ret
python
def record_set_absent(name, zone_name, resource_group, connection_auth=None): ''' .. versionadded:: Fluorine Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name of the DNS zone. :param resource_group: The resource group assigned to the DNS zone. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rec_set = __salt__['azurearm_dns.record_set_get']( name, zone_name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rec_set: ret['result'] = True ret['comment'] = 'Record set {0} was not found in zone {1}.'.format(name, zone_name) return ret elif __opts__['test']: ret['comment'] = 'Record set {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rec_set, 'new': {}, } return ret deleted = __salt__['azurearm_dns.record_set_delete'](name, zone_name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Record set {0} has been deleted.'.format(name) ret['changes'] = { 'old': rec_set, 'new': {} } return ret ret['comment'] = 'Failed to delete record set {0}!'.format(name) return ret
[ "def", "record_set_absent", "(", "name", ",", "zone_name", ",", "resource_group", ",", "connection_auth", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{...
.. versionadded:: Fluorine Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name of the DNS zone. :param resource_group: The resource group assigned to the DNS zone. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API.
[ "..", "versionadded", "::", "Fluorine" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_dns.py#L619-L683
train
saltstack/salt
salt/modules/portage_config.py
_get_config_file
def _get_config_file(conf, atom): ''' Parse the given atom, allowing access to its parts Success does not mean that the atom exists, just that it is in the correct format. Returns none if the atom is invalid. ''' if '*' in atom: parts = portage.dep.Atom(atom, allow_wildcard=True) if not parts: return if parts.cp == '*/*': # parts.repo will be empty if there is no repo part relative_path = parts.repo or "gentoo" elif six.text_type(parts.cp).endswith('/*'): relative_path = six.text_type(parts.cp).split("/")[0] + "_" else: relative_path = os.path.join(*[x for x in os.path.split(parts.cp) if x != '*']) else: relative_path = _p_to_cp(atom) if not relative_path: return complete_file_path = BASE_PATH.format(conf) + '/' + relative_path return complete_file_path
python
def _get_config_file(conf, atom): ''' Parse the given atom, allowing access to its parts Success does not mean that the atom exists, just that it is in the correct format. Returns none if the atom is invalid. ''' if '*' in atom: parts = portage.dep.Atom(atom, allow_wildcard=True) if not parts: return if parts.cp == '*/*': # parts.repo will be empty if there is no repo part relative_path = parts.repo or "gentoo" elif six.text_type(parts.cp).endswith('/*'): relative_path = six.text_type(parts.cp).split("/")[0] + "_" else: relative_path = os.path.join(*[x for x in os.path.split(parts.cp) if x != '*']) else: relative_path = _p_to_cp(atom) if not relative_path: return complete_file_path = BASE_PATH.format(conf) + '/' + relative_path return complete_file_path
[ "def", "_get_config_file", "(", "conf", ",", "atom", ")", ":", "if", "'*'", "in", "atom", ":", "parts", "=", "portage", ".", "dep", ".", "Atom", "(", "atom", ",", "allow_wildcard", "=", "True", ")", "if", "not", "parts", ":", "return", "if", "parts",...
Parse the given atom, allowing access to its parts Success does not mean that the atom exists, just that it is in the correct format. Returns none if the atom is invalid.
[ "Parse", "the", "given", "atom", "allowing", "access", "to", "its", "parts", "Success", "does", "not", "mean", "that", "the", "atom", "exists", "just", "that", "it", "is", "in", "the", "correct", "format", ".", "Returns", "none", "if", "the", "atom", "is...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L68-L93
train
saltstack/salt
salt/modules/portage_config.py
_get_cpv
def _get_cpv(cp, installed=True): ''' add version to category/package @cp - name of package in format category/name @installed - boolean value, if False, function returns cpv for latest available package ''' if installed: return _get_portage().db[portage.root]['vartree'].dep_bestmatch(cp) else: return _porttree().dep_bestmatch(cp)
python
def _get_cpv(cp, installed=True): ''' add version to category/package @cp - name of package in format category/name @installed - boolean value, if False, function returns cpv for latest available package ''' if installed: return _get_portage().db[portage.root]['vartree'].dep_bestmatch(cp) else: return _porttree().dep_bestmatch(cp)
[ "def", "_get_cpv", "(", "cp", ",", "installed", "=", "True", ")", ":", "if", "installed", ":", "return", "_get_portage", "(", ")", ".", "db", "[", "portage", ".", "root", "]", "[", "'vartree'", "]", ".", "dep_bestmatch", "(", "cp", ")", "else", ":", ...
add version to category/package @cp - name of package in format category/name @installed - boolean value, if False, function returns cpv for latest available package
[ "add", "version", "to", "category", "/", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L125-L135
train
saltstack/salt
salt/modules/portage_config.py
_unify_keywords
def _unify_keywords(): ''' Merge /etc/portage/package.keywords and /etc/portage/package.accept_keywords. ''' old_path = BASE_PATH.format('keywords') if os.path.exists(old_path): if os.path.isdir(old_path): for triplet in salt.utils.path.os_walk(old_path): for file_name in triplet[2]: file_path = '{0}/{1}'.format(triplet[0], file_name) with salt.utils.files.fopen(file_path) as fh_: for line in fh_: line = salt.utils.stringutils.to_unicode(line).strip() if line and not line.startswith('#'): append_to_package_conf( 'accept_keywords', string=line) shutil.rmtree(old_path) else: with salt.utils.files.fopen(old_path) as fh_: for line in fh_: line = salt.utils.stringutils.to_unicode(line).strip() if line and not line.startswith('#'): append_to_package_conf('accept_keywords', string=line) os.remove(old_path)
python
def _unify_keywords(): ''' Merge /etc/portage/package.keywords and /etc/portage/package.accept_keywords. ''' old_path = BASE_PATH.format('keywords') if os.path.exists(old_path): if os.path.isdir(old_path): for triplet in salt.utils.path.os_walk(old_path): for file_name in triplet[2]: file_path = '{0}/{1}'.format(triplet[0], file_name) with salt.utils.files.fopen(file_path) as fh_: for line in fh_: line = salt.utils.stringutils.to_unicode(line).strip() if line and not line.startswith('#'): append_to_package_conf( 'accept_keywords', string=line) shutil.rmtree(old_path) else: with salt.utils.files.fopen(old_path) as fh_: for line in fh_: line = salt.utils.stringutils.to_unicode(line).strip() if line and not line.startswith('#'): append_to_package_conf('accept_keywords', string=line) os.remove(old_path)
[ "def", "_unify_keywords", "(", ")", ":", "old_path", "=", "BASE_PATH", ".", "format", "(", "'keywords'", ")", "if", "os", ".", "path", ".", "exists", "(", "old_path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "old_path", ")", ":", "for", ...
Merge /etc/portage/package.keywords and /etc/portage/package.accept_keywords.
[ "Merge", "/", "etc", "/", "portage", "/", "package", ".", "keywords", "and", "/", "etc", "/", "portage", "/", "package", ".", "accept_keywords", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L176-L200
train
saltstack/salt
salt/modules/portage_config.py
_package_conf_file_to_dir
def _package_conf_file_to_dir(file_name): ''' Convert a config file to a config directory. ''' if file_name in SUPPORTED_CONFS: path = BASE_PATH.format(file_name) if os.path.exists(path): if os.path.isdir(path): return False else: os.rename(path, path + '.tmpbak') os.mkdir(path, 0o755) os.rename(path + '.tmpbak', os.path.join(path, 'tmp')) return True else: os.mkdir(path, 0o755) return True
python
def _package_conf_file_to_dir(file_name): ''' Convert a config file to a config directory. ''' if file_name in SUPPORTED_CONFS: path = BASE_PATH.format(file_name) if os.path.exists(path): if os.path.isdir(path): return False else: os.rename(path, path + '.tmpbak') os.mkdir(path, 0o755) os.rename(path + '.tmpbak', os.path.join(path, 'tmp')) return True else: os.mkdir(path, 0o755) return True
[ "def", "_package_conf_file_to_dir", "(", "file_name", ")", ":", "if", "file_name", "in", "SUPPORTED_CONFS", ":", "path", "=", "BASE_PATH", ".", "format", "(", "file_name", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "os", "....
Convert a config file to a config directory.
[ "Convert", "a", "config", "file", "to", "a", "config", "directory", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L203-L219
train
saltstack/salt
salt/modules/portage_config.py
_package_conf_ordering
def _package_conf_ordering(conf, clean=True, keep_backup=False): ''' Move entries in the correct file. ''' if conf in SUPPORTED_CONFS: rearrange = [] path = BASE_PATH.format(conf) backup_files = [] for triplet in salt.utils.path.os_walk(path): for file_name in triplet[2]: file_path = '{0}/{1}'.format(triplet[0], file_name) cp = triplet[0][len(path) + 1:] + '/' + file_name shutil.copy(file_path, file_path + '.bak') backup_files.append(file_path + '.bak') if cp[0] == '/' or len(cp.split('/')) > 2: with salt.utils.files.fopen(file_path) as fp_: rearrange.extend(salt.utils.data.decode(fp_.readlines())) os.remove(file_path) else: new_contents = '' with salt.utils.files.fopen(file_path, 'r+') as file_handler: for line in file_handler: line = salt.utils.stringutils.to_unicode(line) try: atom = line.strip().split()[0] except IndexError: new_contents += line else: if atom[0] == '#' or \ portage.dep_getkey(atom) == cp: new_contents += line else: rearrange.append(line.strip()) if new_contents: file_handler.seek(0) file_handler.truncate(len(new_contents)) file_handler.write(new_contents) if not new_contents: os.remove(file_path) for line in rearrange: append_to_package_conf(conf, string=line) if not keep_backup: for bfile in backup_files: try: os.remove(bfile) except OSError: pass if clean: for triplet in salt.utils.path.os_walk(path): if not triplet[1] and not triplet[2] and triplet[0] != path: shutil.rmtree(triplet[0])
python
def _package_conf_ordering(conf, clean=True, keep_backup=False): ''' Move entries in the correct file. ''' if conf in SUPPORTED_CONFS: rearrange = [] path = BASE_PATH.format(conf) backup_files = [] for triplet in salt.utils.path.os_walk(path): for file_name in triplet[2]: file_path = '{0}/{1}'.format(triplet[0], file_name) cp = triplet[0][len(path) + 1:] + '/' + file_name shutil.copy(file_path, file_path + '.bak') backup_files.append(file_path + '.bak') if cp[0] == '/' or len(cp.split('/')) > 2: with salt.utils.files.fopen(file_path) as fp_: rearrange.extend(salt.utils.data.decode(fp_.readlines())) os.remove(file_path) else: new_contents = '' with salt.utils.files.fopen(file_path, 'r+') as file_handler: for line in file_handler: line = salt.utils.stringutils.to_unicode(line) try: atom = line.strip().split()[0] except IndexError: new_contents += line else: if atom[0] == '#' or \ portage.dep_getkey(atom) == cp: new_contents += line else: rearrange.append(line.strip()) if new_contents: file_handler.seek(0) file_handler.truncate(len(new_contents)) file_handler.write(new_contents) if not new_contents: os.remove(file_path) for line in rearrange: append_to_package_conf(conf, string=line) if not keep_backup: for bfile in backup_files: try: os.remove(bfile) except OSError: pass if clean: for triplet in salt.utils.path.os_walk(path): if not triplet[1] and not triplet[2] and triplet[0] != path: shutil.rmtree(triplet[0])
[ "def", "_package_conf_ordering", "(", "conf", ",", "clean", "=", "True", ",", "keep_backup", "=", "False", ")", ":", "if", "conf", "in", "SUPPORTED_CONFS", ":", "rearrange", "=", "[", "]", "path", "=", "BASE_PATH", ".", "format", "(", "conf", ")", "backu...
Move entries in the correct file.
[ "Move", "entries", "in", "the", "correct", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L222-L280
train
saltstack/salt
salt/modules/portage_config.py
_check_accept_keywords
def _check_accept_keywords(approved, flag): '''check compatibility of accept_keywords''' if flag in approved: return False elif (flag.startswith('~') and flag[1:] in approved) \ or ('~'+flag in approved): return False else: return True
python
def _check_accept_keywords(approved, flag): '''check compatibility of accept_keywords''' if flag in approved: return False elif (flag.startswith('~') and flag[1:] in approved) \ or ('~'+flag in approved): return False else: return True
[ "def", "_check_accept_keywords", "(", "approved", ",", "flag", ")", ":", "if", "flag", "in", "approved", ":", "return", "False", "elif", "(", "flag", ".", "startswith", "(", "'~'", ")", "and", "flag", "[", "1", ":", "]", "in", "approved", ")", "or", ...
check compatibility of accept_keywords
[ "check", "compatibility", "of", "accept_keywords" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L283-L291
train
saltstack/salt
salt/modules/portage_config.py
_merge_flags
def _merge_flags(new_flags, old_flags=None, conf='any'): ''' Merges multiple lists of flags removing duplicates and resolving conflicts giving priority to lasts lists. ''' if not old_flags: old_flags = [] args = [old_flags, new_flags] if conf == 'accept_keywords': tmp = new_flags + \ [i for i in old_flags if _check_accept_keywords(new_flags, i)] else: tmp = portage.flatten(args) flags = {} for flag in tmp: if flag[0] == '-': flags[flag[1:]] = False else: flags[flag] = True tmp = [] for key, val in six.iteritems(flags): if val: tmp.append(key) else: tmp.append('-' + key) # Next sort is just aesthetic, can be commented for a small performance # boost tmp.sort(key=lambda x: x.lstrip('-')) return tmp
python
def _merge_flags(new_flags, old_flags=None, conf='any'): ''' Merges multiple lists of flags removing duplicates and resolving conflicts giving priority to lasts lists. ''' if not old_flags: old_flags = [] args = [old_flags, new_flags] if conf == 'accept_keywords': tmp = new_flags + \ [i for i in old_flags if _check_accept_keywords(new_flags, i)] else: tmp = portage.flatten(args) flags = {} for flag in tmp: if flag[0] == '-': flags[flag[1:]] = False else: flags[flag] = True tmp = [] for key, val in six.iteritems(flags): if val: tmp.append(key) else: tmp.append('-' + key) # Next sort is just aesthetic, can be commented for a small performance # boost tmp.sort(key=lambda x: x.lstrip('-')) return tmp
[ "def", "_merge_flags", "(", "new_flags", ",", "old_flags", "=", "None", ",", "conf", "=", "'any'", ")", ":", "if", "not", "old_flags", ":", "old_flags", "=", "[", "]", "args", "=", "[", "old_flags", ",", "new_flags", "]", "if", "conf", "==", "'accept_k...
Merges multiple lists of flags removing duplicates and resolving conflicts giving priority to lasts lists.
[ "Merges", "multiple", "lists", "of", "flags", "removing", "duplicates", "and", "resolving", "conflicts", "giving", "priority", "to", "lasts", "lists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L294-L323
train
saltstack/salt
salt/modules/portage_config.py
append_to_package_conf
def append_to_package_conf(conf, atom='', flags=None, string='', overwrite=False): ''' Append a string or a list of flags for a given package or DEPEND atom to a given configuration file. CLI Example: .. code-block:: bash salt '*' portage_config.append_to_package_conf use string="app-admin/salt ldap -libvirt" salt '*' portage_config.append_to_package_conf use atom="> = app-admin/salt-0.14.1" flags="['ldap', '-libvirt']" ''' if flags is None: flags = [] if conf in SUPPORTED_CONFS: if not string: if '/' not in atom: atom = _p_to_cp(atom) if not atom: return string = '{0} {1}'.format(atom, ' '.join(flags)) new_flags = list(flags) else: atom = string.strip().split()[0] new_flags = [flag for flag in string.strip().split(' ') if flag][1:] if '/' not in atom: atom = _p_to_cp(atom) string = '{0} {1}'.format(atom, ' '.join(new_flags)) if not atom: return to_delete_if_empty = [] if conf == 'accept_keywords': if '-~ARCH' in new_flags: new_flags.remove('-~ARCH') to_delete_if_empty.append(atom) if '~ARCH' in new_flags: new_flags.remove('~ARCH') append_to_package_conf(conf, string=atom, overwrite=overwrite) if not new_flags: return # Next sort is just aesthetic, can be commented for a small performance # boost new_flags.sort(key=lambda x: x.lstrip('-')) complete_file_path = _get_config_file(conf, atom) pdir = os.path.dirname(complete_file_path) if not os.path.exists(pdir): os.makedirs(pdir, 0o755) try: shutil.copy(complete_file_path, complete_file_path + '.bak') except IOError: pass try: file_handler = salt.utils.files.fopen(complete_file_path, 'r+') # pylint: disable=resource-leakage except IOError: file_handler = salt.utils.files.fopen(complete_file_path, 'w+') # pylint: disable=resource-leakage new_contents = '' added = False try: for l in file_handler: l_strip = l.strip() if l_strip == '': new_contents += '\n' elif l_strip[0] == '#': new_contents += l elif l_strip.split()[0] == atom: if l_strip in to_delete_if_empty: continue if overwrite: new_contents += string.strip() + '\n' added = True else: old_flags = [flag for flag in l_strip.split(' ') if flag][1:] if conf == 'accept_keywords': if not old_flags: new_contents += l if not new_flags: added = True continue elif not new_flags: continue merged_flags = _merge_flags(new_flags, old_flags, conf) if merged_flags: new_contents += '{0} {1}\n'.format( atom, ' '.join(merged_flags)) else: new_contents += '{0}\n'.format(atom) added = True else: new_contents += l if not added: new_contents += string.strip() + '\n' except Exception as exc: log.error('Failed to write to %s: %s', complete_file_path, exc) else: file_handler.seek(0) file_handler.truncate(len(new_contents)) file_handler.write(new_contents) finally: file_handler.close() try: os.remove(complete_file_path + '.bak') except OSError: pass
python
def append_to_package_conf(conf, atom='', flags=None, string='', overwrite=False): ''' Append a string or a list of flags for a given package or DEPEND atom to a given configuration file. CLI Example: .. code-block:: bash salt '*' portage_config.append_to_package_conf use string="app-admin/salt ldap -libvirt" salt '*' portage_config.append_to_package_conf use atom="> = app-admin/salt-0.14.1" flags="['ldap', '-libvirt']" ''' if flags is None: flags = [] if conf in SUPPORTED_CONFS: if not string: if '/' not in atom: atom = _p_to_cp(atom) if not atom: return string = '{0} {1}'.format(atom, ' '.join(flags)) new_flags = list(flags) else: atom = string.strip().split()[0] new_flags = [flag for flag in string.strip().split(' ') if flag][1:] if '/' not in atom: atom = _p_to_cp(atom) string = '{0} {1}'.format(atom, ' '.join(new_flags)) if not atom: return to_delete_if_empty = [] if conf == 'accept_keywords': if '-~ARCH' in new_flags: new_flags.remove('-~ARCH') to_delete_if_empty.append(atom) if '~ARCH' in new_flags: new_flags.remove('~ARCH') append_to_package_conf(conf, string=atom, overwrite=overwrite) if not new_flags: return # Next sort is just aesthetic, can be commented for a small performance # boost new_flags.sort(key=lambda x: x.lstrip('-')) complete_file_path = _get_config_file(conf, atom) pdir = os.path.dirname(complete_file_path) if not os.path.exists(pdir): os.makedirs(pdir, 0o755) try: shutil.copy(complete_file_path, complete_file_path + '.bak') except IOError: pass try: file_handler = salt.utils.files.fopen(complete_file_path, 'r+') # pylint: disable=resource-leakage except IOError: file_handler = salt.utils.files.fopen(complete_file_path, 'w+') # pylint: disable=resource-leakage new_contents = '' added = False try: for l in file_handler: l_strip = l.strip() if l_strip == '': new_contents += '\n' elif l_strip[0] == '#': new_contents += l elif l_strip.split()[0] == atom: if l_strip in to_delete_if_empty: continue if overwrite: new_contents += string.strip() + '\n' added = True else: old_flags = [flag for flag in l_strip.split(' ') if flag][1:] if conf == 'accept_keywords': if not old_flags: new_contents += l if not new_flags: added = True continue elif not new_flags: continue merged_flags = _merge_flags(new_flags, old_flags, conf) if merged_flags: new_contents += '{0} {1}\n'.format( atom, ' '.join(merged_flags)) else: new_contents += '{0}\n'.format(atom) added = True else: new_contents += l if not added: new_contents += string.strip() + '\n' except Exception as exc: log.error('Failed to write to %s: %s', complete_file_path, exc) else: file_handler.seek(0) file_handler.truncate(len(new_contents)) file_handler.write(new_contents) finally: file_handler.close() try: os.remove(complete_file_path + '.bak') except OSError: pass
[ "def", "append_to_package_conf", "(", "conf", ",", "atom", "=", "''", ",", "flags", "=", "None", ",", "string", "=", "''", ",", "overwrite", "=", "False", ")", ":", "if", "flags", "is", "None", ":", "flags", "=", "[", "]", "if", "conf", "in", "SUPP...
Append a string or a list of flags for a given package or DEPEND atom to a given configuration file. CLI Example: .. code-block:: bash salt '*' portage_config.append_to_package_conf use string="app-admin/salt ldap -libvirt" salt '*' portage_config.append_to_package_conf use atom="> = app-admin/salt-0.14.1" flags="['ldap', '-libvirt']"
[ "Append", "a", "string", "or", "a", "list", "of", "flags", "for", "a", "given", "package", "or", "DEPEND", "atom", "to", "a", "given", "configuration", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L326-L437
train
saltstack/salt
salt/modules/portage_config.py
append_use_flags
def append_use_flags(atom, uses=None, overwrite=False): ''' Append a list of use flags for a given package or DEPEND atom CLI Example: .. code-block:: bash salt '*' portage_config.append_use_flags "app-admin/salt[ldap, -libvirt]" salt '*' portage_config.append_use_flags ">=app-admin/salt-0.14.1" "['ldap', '-libvirt']" ''' if not uses: uses = portage.dep.dep_getusedeps(atom) if not uses: return atom = atom[:atom.rfind('[')] append_to_package_conf('use', atom=atom, flags=uses, overwrite=overwrite)
python
def append_use_flags(atom, uses=None, overwrite=False): ''' Append a list of use flags for a given package or DEPEND atom CLI Example: .. code-block:: bash salt '*' portage_config.append_use_flags "app-admin/salt[ldap, -libvirt]" salt '*' portage_config.append_use_flags ">=app-admin/salt-0.14.1" "['ldap', '-libvirt']" ''' if not uses: uses = portage.dep.dep_getusedeps(atom) if not uses: return atom = atom[:atom.rfind('[')] append_to_package_conf('use', atom=atom, flags=uses, overwrite=overwrite)
[ "def", "append_use_flags", "(", "atom", ",", "uses", "=", "None", ",", "overwrite", "=", "False", ")", ":", "if", "not", "uses", ":", "uses", "=", "portage", ".", "dep", ".", "dep_getusedeps", "(", "atom", ")", "if", "not", "uses", ":", "return", "at...
Append a list of use flags for a given package or DEPEND atom CLI Example: .. code-block:: bash salt '*' portage_config.append_use_flags "app-admin/salt[ldap, -libvirt]" salt '*' portage_config.append_use_flags ">=app-admin/salt-0.14.1" "['ldap', '-libvirt']"
[ "Append", "a", "list", "of", "use", "flags", "for", "a", "given", "package", "or", "DEPEND", "atom" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L440-L456
train