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_efs.py
_get_conn
def _get_conn(key=None, keyid=None, profile=None, region=None, **kwargs): ''' Create a boto3 client connection to EFS ''' client = None if profile: if isinstance(profile, six.string_types): if profile in __pillar__: profile = __pillar__[profile] elif profile in __opts__: profile = __opts__[profile] elif key or keyid or region: profile = {} if key: profile['key'] = key if keyid: profile['keyid'] = keyid if region: profile['region'] = region if isinstance(profile, dict): if 'region' in profile: profile['region_name'] = profile['region'] profile.pop('region', None) if 'key' in profile: profile['aws_secret_access_key'] = profile['key'] profile.pop('key', None) if 'keyid' in profile: profile['aws_access_key_id'] = profile['keyid'] profile.pop('keyid', None) client = boto3.client('efs', **profile) else: client = boto3.client('efs') return client
python
def _get_conn(key=None, keyid=None, profile=None, region=None, **kwargs): ''' Create a boto3 client connection to EFS ''' client = None if profile: if isinstance(profile, six.string_types): if profile in __pillar__: profile = __pillar__[profile] elif profile in __opts__: profile = __opts__[profile] elif key or keyid or region: profile = {} if key: profile['key'] = key if keyid: profile['keyid'] = keyid if region: profile['region'] = region if isinstance(profile, dict): if 'region' in profile: profile['region_name'] = profile['region'] profile.pop('region', None) if 'key' in profile: profile['aws_secret_access_key'] = profile['key'] profile.pop('key', None) if 'keyid' in profile: profile['aws_access_key_id'] = profile['keyid'] profile.pop('keyid', None) client = boto3.client('efs', **profile) else: client = boto3.client('efs') return client
[ "def", "_get_conn", "(", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "None", "if", "profile", ":", "if", "isinstance", "(", "profile", ","...
Create a boto3 client connection to EFS
[ "Create", "a", "boto3", "client", "connection", "to", "EFS" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L82-L121
train
saltstack/salt
salt/modules/boto_efs.py
create_file_system
def create_file_system(name, performance_mode='generalPurpose', keyid=None, key=None, profile=None, region=None, creation_token=None, **kwargs): ''' Creates a new, empty file system. name (string) - The name for the new file system performance_mode (string) - The PerformanceMode of the file system. Can be either generalPurpose or maxIO creation_token (string) - A unique name to be used as reference when creating an EFS. This will ensure idempotency. Set to name if not specified otherwise returns (dict) - A dict of the data for the elastic file system CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.create_file_system efs-name generalPurpose ''' if creation_token is None: creation_token = name tags = {"Key": "Name", "Value": name} client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) response = client.create_file_system(CreationToken=creation_token, PerformanceMode=performance_mode) if 'FileSystemId' in response: client.create_tags(FileSystemId=response['FileSystemId'], Tags=tags) if 'Name' in response: response['Name'] = name return response
python
def create_file_system(name, performance_mode='generalPurpose', keyid=None, key=None, profile=None, region=None, creation_token=None, **kwargs): ''' Creates a new, empty file system. name (string) - The name for the new file system performance_mode (string) - The PerformanceMode of the file system. Can be either generalPurpose or maxIO creation_token (string) - A unique name to be used as reference when creating an EFS. This will ensure idempotency. Set to name if not specified otherwise returns (dict) - A dict of the data for the elastic file system CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.create_file_system efs-name generalPurpose ''' if creation_token is None: creation_token = name tags = {"Key": "Name", "Value": name} client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) response = client.create_file_system(CreationToken=creation_token, PerformanceMode=performance_mode) if 'FileSystemId' in response: client.create_tags(FileSystemId=response['FileSystemId'], Tags=tags) if 'Name' in response: response['Name'] = name return response
[ "def", "create_file_system", "(", "name", ",", "performance_mode", "=", "'generalPurpose'", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "creation_token", "=", "None", ",", "*", "*", "k...
Creates a new, empty file system. name (string) - The name for the new file system performance_mode (string) - The PerformanceMode of the file system. Can be either generalPurpose or maxIO creation_token (string) - A unique name to be used as reference when creating an EFS. This will ensure idempotency. Set to name if not specified otherwise returns (dict) - A dict of the data for the elastic file system CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.create_file_system efs-name generalPurpose
[ "Creates", "a", "new", "empty", "file", "system", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L124-L172
train
saltstack/salt
salt/modules/boto_efs.py
create_mount_target
def create_mount_target(filesystemid, subnetid, ipaddress=None, securitygroups=None, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Creates a mount target for a file system. You can then mount the file system on EC2 instances via the mount target. You can create one mount target in each Availability Zone in your VPC. All EC2 instances in a VPC within a given Availability Zone share a single mount target for a given file system. If you have multiple subnets in an Availability Zone, you create a mount target in one of the subnets. EC2 instances do not need to be in the same subnet as the mount target in order to access their file system. filesystemid (string) - ID of the file system for which to create the mount target. subnetid (string) - ID of the subnet to add the mount target in. ipaddress (string) - Valid IPv4 address within the address range of the specified subnet. securitygroups (list[string]) - Up to five VPC security group IDs, of the form sg-xxxxxxxx. These must be for the same VPC as subnet specified. returns (dict) - A dict of the response data CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.create_mount_target filesystemid subnetid ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) if ipaddress is None and securitygroups is None: return client.create_mount_target(FileSystemId=filesystemid, SubnetId=subnetid) if ipaddress is None: return client.create_mount_target(FileSystemId=filesystemid, SubnetId=subnetid, SecurityGroups=securitygroups) if securitygroups is None: return client.create_mount_target(FileSystemId=filesystemid, SubnetId=subnetid, IpAddress=ipaddress) return client.create_mount_target(FileSystemId=filesystemid, SubnetId=subnetid, IpAddress=ipaddress, SecurityGroups=securitygroups)
python
def create_mount_target(filesystemid, subnetid, ipaddress=None, securitygroups=None, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Creates a mount target for a file system. You can then mount the file system on EC2 instances via the mount target. You can create one mount target in each Availability Zone in your VPC. All EC2 instances in a VPC within a given Availability Zone share a single mount target for a given file system. If you have multiple subnets in an Availability Zone, you create a mount target in one of the subnets. EC2 instances do not need to be in the same subnet as the mount target in order to access their file system. filesystemid (string) - ID of the file system for which to create the mount target. subnetid (string) - ID of the subnet to add the mount target in. ipaddress (string) - Valid IPv4 address within the address range of the specified subnet. securitygroups (list[string]) - Up to five VPC security group IDs, of the form sg-xxxxxxxx. These must be for the same VPC as subnet specified. returns (dict) - A dict of the response data CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.create_mount_target filesystemid subnetid ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) if ipaddress is None and securitygroups is None: return client.create_mount_target(FileSystemId=filesystemid, SubnetId=subnetid) if ipaddress is None: return client.create_mount_target(FileSystemId=filesystemid, SubnetId=subnetid, SecurityGroups=securitygroups) if securitygroups is None: return client.create_mount_target(FileSystemId=filesystemid, SubnetId=subnetid, IpAddress=ipaddress) return client.create_mount_target(FileSystemId=filesystemid, SubnetId=subnetid, IpAddress=ipaddress, SecurityGroups=securitygroups)
[ "def", "create_mount_target", "(", "filesystemid", ",", "subnetid", ",", "ipaddress", "=", "None", ",", "securitygroups", "=", "None", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", ...
Creates a mount target for a file system. You can then mount the file system on EC2 instances via the mount target. You can create one mount target in each Availability Zone in your VPC. All EC2 instances in a VPC within a given Availability Zone share a single mount target for a given file system. If you have multiple subnets in an Availability Zone, you create a mount target in one of the subnets. EC2 instances do not need to be in the same subnet as the mount target in order to access their file system. filesystemid (string) - ID of the file system for which to create the mount target. subnetid (string) - ID of the subnet to add the mount target in. ipaddress (string) - Valid IPv4 address within the address range of the specified subnet. securitygroups (list[string]) - Up to five VPC security group IDs, of the form sg-xxxxxxxx. These must be for the same VPC as subnet specified. returns (dict) - A dict of the response data CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.create_mount_target filesystemid subnetid
[ "Creates", "a", "mount", "target", "for", "a", "file", "system", ".", "You", "can", "then", "mount", "the", "file", "system", "on", "EC2", "instances", "via", "the", "mount", "target", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L175-L240
train
saltstack/salt
salt/modules/boto_efs.py
create_tags
def create_tags(filesystemid, tags, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Creates or overwrites tags associated with a file system. Each tag is a key-value pair. If a tag key specified in the request already exists on the file system, this operation overwrites its value with the value provided in the request. filesystemid (string) - ID of the file system for whose tags will be modified. tags (dict) - The tags to add to the file system CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.create_tags ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) new_tags = [] for k, v in six.iteritems(tags): new_tags.append({'Key': k, 'Value': v}) client.create_tags(FileSystemId=filesystemid, Tags=new_tags)
python
def create_tags(filesystemid, tags, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Creates or overwrites tags associated with a file system. Each tag is a key-value pair. If a tag key specified in the request already exists on the file system, this operation overwrites its value with the value provided in the request. filesystemid (string) - ID of the file system for whose tags will be modified. tags (dict) - The tags to add to the file system CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.create_tags ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) new_tags = [] for k, v in six.iteritems(tags): new_tags.append({'Key': k, 'Value': v}) client.create_tags(FileSystemId=filesystemid, Tags=new_tags)
[ "def", "create_tags", "(", "filesystemid", ",", "tags", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_conn", "(", "key", "=", "ke...
Creates or overwrites tags associated with a file system. Each tag is a key-value pair. If a tag key specified in the request already exists on the file system, this operation overwrites its value with the value provided in the request. filesystemid (string) - ID of the file system for whose tags will be modified. tags (dict) - The tags to add to the file system CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.create_tags
[ "Creates", "or", "overwrites", "tags", "associated", "with", "a", "file", "system", ".", "Each", "tag", "is", "a", "key", "-", "value", "pair", ".", "If", "a", "tag", "key", "specified", "in", "the", "request", "already", "exists", "on", "the", "file", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L243-L275
train
saltstack/salt
salt/modules/boto_efs.py
delete_file_system
def delete_file_system(filesystemid, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Deletes a file system, permanently severing access to its contents. Upon return, the file system no longer exists and you can't access any contents of the deleted file system. You can't delete a file system that is in use. That is, if the file system has any mount targets, you must first delete them. filesystemid (string) - ID of the file system to delete. CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.delete_file_system filesystemid ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) client.delete_file_system(FileSystemId=filesystemid)
python
def delete_file_system(filesystemid, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Deletes a file system, permanently severing access to its contents. Upon return, the file system no longer exists and you can't access any contents of the deleted file system. You can't delete a file system that is in use. That is, if the file system has any mount targets, you must first delete them. filesystemid (string) - ID of the file system to delete. CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.delete_file_system filesystemid ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) client.delete_file_system(FileSystemId=filesystemid)
[ "def", "delete_file_system", "(", "filesystemid", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_conn", "(", "key", "=", "key", ",",...
Deletes a file system, permanently severing access to its contents. Upon return, the file system no longer exists and you can't access any contents of the deleted file system. You can't delete a file system that is in use. That is, if the file system has any mount targets, you must first delete them. filesystemid (string) - ID of the file system to delete. CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.delete_file_system filesystemid
[ "Deletes", "a", "file", "system", "permanently", "severing", "access", "to", "its", "contents", ".", "Upon", "return", "the", "file", "system", "no", "longer", "exists", "and", "you", "can", "t", "access", "any", "contents", "of", "the", "deleted", "file", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L278-L303
train
saltstack/salt
salt/modules/boto_efs.py
delete_mount_target
def delete_mount_target(mounttargetid, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Deletes the specified mount target. This operation forcibly breaks any mounts of the file system via the mount target that is being deleted, which might disrupt instances or applications using those mounts. To avoid applications getting cut off abruptly, you might consider unmounting any mounts of the mount target, if feasible. The operation also deletes the associated network interface. Uncommitted writes may be lost, but breaking a mount target using this operation does not corrupt the file system itself. The file system you created remains. You can mount an EC2 instance in your VPC via another mount target. mounttargetid (string) - ID of the mount target to delete CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.delete_mount_target mounttargetid ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) client.delete_mount_target(MountTargetId=mounttargetid)
python
def delete_mount_target(mounttargetid, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Deletes the specified mount target. This operation forcibly breaks any mounts of the file system via the mount target that is being deleted, which might disrupt instances or applications using those mounts. To avoid applications getting cut off abruptly, you might consider unmounting any mounts of the mount target, if feasible. The operation also deletes the associated network interface. Uncommitted writes may be lost, but breaking a mount target using this operation does not corrupt the file system itself. The file system you created remains. You can mount an EC2 instance in your VPC via another mount target. mounttargetid (string) - ID of the mount target to delete CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.delete_mount_target mounttargetid ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) client.delete_mount_target(MountTargetId=mounttargetid)
[ "def", "delete_mount_target", "(", "mounttargetid", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_conn", "(", "key", "=", "key", ",...
Deletes the specified mount target. This operation forcibly breaks any mounts of the file system via the mount target that is being deleted, which might disrupt instances or applications using those mounts. To avoid applications getting cut off abruptly, you might consider unmounting any mounts of the mount target, if feasible. The operation also deletes the associated network interface. Uncommitted writes may be lost, but breaking a mount target using this operation does not corrupt the file system itself. The file system you created remains. You can mount an EC2 instance in your VPC via another mount target. mounttargetid (string) - ID of the mount target to delete CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.delete_mount_target mounttargetid
[ "Deletes", "the", "specified", "mount", "target", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L306-L337
train
saltstack/salt
salt/modules/boto_efs.py
delete_tags
def delete_tags(filesystemid, tags, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Deletes the specified tags from a file system. filesystemid (string) - ID of the file system for whose tags will be removed. tags (list[string]) - The tag keys to delete to the file system CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.delete_tags ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) client.delete_tags(FileSystemId=filesystemid, Tags=tags)
python
def delete_tags(filesystemid, tags, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Deletes the specified tags from a file system. filesystemid (string) - ID of the file system for whose tags will be removed. tags (list[string]) - The tag keys to delete to the file system CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.delete_tags ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) client.delete_tags(FileSystemId=filesystemid, Tags=tags)
[ "def", "delete_tags", "(", "filesystemid", ",", "tags", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_conn", "(", "key", "=", "ke...
Deletes the specified tags from a file system. filesystemid (string) - ID of the file system for whose tags will be removed. tags (list[string]) - The tag keys to delete to the file system CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.delete_tags
[ "Deletes", "the", "specified", "tags", "from", "a", "file", "system", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L340-L365
train
saltstack/salt
salt/modules/boto_efs.py
get_file_systems
def get_file_systems(filesystemid=None, keyid=None, key=None, profile=None, region=None, creation_token=None, **kwargs): ''' Get all EFS properties or a specific instance property if filesystemid is specified filesystemid (string) - ID of the file system to retrieve properties creation_token (string) - A unique token that identifies an EFS. If fileysystem created via create_file_system this would either be explictitly passed in or set to name. You can limit your search with this. returns (list[dict]) - list of all elastic file system properties CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.get_file_systems efs-id ''' result = None client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) if filesystemid and creation_token: response = client.describe_file_systems(FileSystemId=filesystemid, CreationToken=creation_token) result = response["FileSystems"] elif filesystemid: response = client.describe_file_systems(FileSystemId=filesystemid) result = response["FileSystems"] elif creation_token: response = client.describe_file_systems(CreationToken=creation_token) result = response["FileSystems"] else: response = client.describe_file_systems() result = response["FileSystems"] while "NextMarker" in response: response = client.describe_file_systems( Marker=response["NextMarker"]) result.extend(response["FileSystems"]) return result
python
def get_file_systems(filesystemid=None, keyid=None, key=None, profile=None, region=None, creation_token=None, **kwargs): ''' Get all EFS properties or a specific instance property if filesystemid is specified filesystemid (string) - ID of the file system to retrieve properties creation_token (string) - A unique token that identifies an EFS. If fileysystem created via create_file_system this would either be explictitly passed in or set to name. You can limit your search with this. returns (list[dict]) - list of all elastic file system properties CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.get_file_systems efs-id ''' result = None client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) if filesystemid and creation_token: response = client.describe_file_systems(FileSystemId=filesystemid, CreationToken=creation_token) result = response["FileSystems"] elif filesystemid: response = client.describe_file_systems(FileSystemId=filesystemid) result = response["FileSystems"] elif creation_token: response = client.describe_file_systems(CreationToken=creation_token) result = response["FileSystems"] else: response = client.describe_file_systems() result = response["FileSystems"] while "NextMarker" in response: response = client.describe_file_systems( Marker=response["NextMarker"]) result.extend(response["FileSystems"]) return result
[ "def", "get_file_systems", "(", "filesystemid", "=", "None", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "creation_token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "result", ...
Get all EFS properties or a specific instance property if filesystemid is specified filesystemid (string) - ID of the file system to retrieve properties creation_token (string) - A unique token that identifies an EFS. If fileysystem created via create_file_system this would either be explictitly passed in or set to name. You can limit your search with this. returns (list[dict]) - list of all elastic file system properties CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.get_file_systems efs-id
[ "Get", "all", "EFS", "properties", "or", "a", "specific", "instance", "property", "if", "filesystemid", "is", "specified" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L368-L421
train
saltstack/salt
salt/modules/boto_efs.py
get_mount_targets
def get_mount_targets(filesystemid=None, mounttargetid=None, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Get all the EFS mount point properties for a specific filesystemid or the properties for a specific mounttargetid. One or the other must be specified filesystemid (string) - ID of the file system whose mount targets to list Must be specified if mounttargetid is not mounttargetid (string) - ID of the mount target to have its properties returned Must be specified if filesystemid is not returns (list[dict]) - list of all mount point properties CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.get_mount_targets ''' result = None client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) if filesystemid: response = client.describe_mount_targets(FileSystemId=filesystemid) result = response["MountTargets"] while "NextMarker" in response: response = client.describe_mount_targets(FileSystemId=filesystemid, Marker=response["NextMarker"]) result.extend(response["MountTargets"]) elif mounttargetid: response = client.describe_mount_targets(MountTargetId=mounttargetid) result = response["MountTargets"] return result
python
def get_mount_targets(filesystemid=None, mounttargetid=None, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Get all the EFS mount point properties for a specific filesystemid or the properties for a specific mounttargetid. One or the other must be specified filesystemid (string) - ID of the file system whose mount targets to list Must be specified if mounttargetid is not mounttargetid (string) - ID of the mount target to have its properties returned Must be specified if filesystemid is not returns (list[dict]) - list of all mount point properties CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.get_mount_targets ''' result = None client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) if filesystemid: response = client.describe_mount_targets(FileSystemId=filesystemid) result = response["MountTargets"] while "NextMarker" in response: response = client.describe_mount_targets(FileSystemId=filesystemid, Marker=response["NextMarker"]) result.extend(response["MountTargets"]) elif mounttargetid: response = client.describe_mount_targets(MountTargetId=mounttargetid) result = response["MountTargets"] return result
[ "def", "get_mount_targets", "(", "filesystemid", "=", "None", ",", "mounttargetid", "=", "None", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "result", ...
Get all the EFS mount point properties for a specific filesystemid or the properties for a specific mounttargetid. One or the other must be specified filesystemid (string) - ID of the file system whose mount targets to list Must be specified if mounttargetid is not mounttargetid (string) - ID of the mount target to have its properties returned Must be specified if filesystemid is not returns (list[dict]) - list of all mount point properties CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.get_mount_targets
[ "Get", "all", "the", "EFS", "mount", "point", "properties", "for", "a", "specific", "filesystemid", "or", "the", "properties", "for", "a", "specific", "mounttargetid", ".", "One", "or", "the", "other", "must", "be", "specified" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L424-L468
train
saltstack/salt
salt/modules/boto_efs.py
get_tags
def get_tags(filesystemid, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Return the tags associated with an EFS instance. filesystemid (string) - ID of the file system whose tags to list returns (list) - list of tags as key/value pairs CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.get_tags efs-id ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) response = client.describe_tags(FileSystemId=filesystemid) result = response["Tags"] while "NextMarker" in response: response = client.describe_tags(FileSystemId=filesystemid, Marker=response["NextMarker"]) result.extend(response["Tags"]) return result
python
def get_tags(filesystemid, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Return the tags associated with an EFS instance. filesystemid (string) - ID of the file system whose tags to list returns (list) - list of tags as key/value pairs CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.get_tags efs-id ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) response = client.describe_tags(FileSystemId=filesystemid) result = response["Tags"] while "NextMarker" in response: response = client.describe_tags(FileSystemId=filesystemid, Marker=response["NextMarker"]) result.extend(response["Tags"]) return result
[ "def", "get_tags", "(", "filesystemid", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_conn", "(", "key", "=", "key", ",", "keyid"...
Return the tags associated with an EFS instance. filesystemid (string) - ID of the file system whose tags to list returns (list) - list of tags as key/value pairs CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.get_tags efs-id
[ "Return", "the", "tags", "associated", "with", "an", "EFS", "instance", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L471-L501
train
saltstack/salt
salt/modules/boto_efs.py
set_security_groups
def set_security_groups(mounttargetid, securitygroup, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Modifies the set of security groups in effect for a mount target mounttargetid (string) - ID of the mount target whose security groups will be modified securitygroups (list[string]) - list of no more than 5 VPC security group IDs. CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.set_security_groups my-mount-target-id my-sec-group ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) client.modify_mount_target_security_groups(MountTargetId=mounttargetid, SecurityGroups=securitygroup)
python
def set_security_groups(mounttargetid, securitygroup, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Modifies the set of security groups in effect for a mount target mounttargetid (string) - ID of the mount target whose security groups will be modified securitygroups (list[string]) - list of no more than 5 VPC security group IDs. CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.set_security_groups my-mount-target-id my-sec-group ''' client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) client.modify_mount_target_security_groups(MountTargetId=mounttargetid, SecurityGroups=securitygroup)
[ "def", "set_security_groups", "(", "mounttargetid", ",", "securitygroup", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_conn", "(", "...
Modifies the set of security groups in effect for a mount target mounttargetid (string) - ID of the mount target whose security groups will be modified securitygroups (list[string]) - list of no more than 5 VPC security group IDs. CLI Example: .. code-block:: bash salt 'my-minion' boto_efs.set_security_groups my-mount-target-id my-sec-group
[ "Modifies", "the", "set", "of", "security", "groups", "in", "effect", "for", "a", "mount", "target" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L504-L529
train
saltstack/salt
salt/states/win_wusa.py
installed
def installed(name, source): ''' Ensure an update is installed on the minion Args: name(str): Name of the Windows KB ("KB123456") source (str): Source of .msu file corresponding to the KB Example: .. code-block:: yaml KB123456: wusa.installed: - source: salt://kb123456.msu ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Input validation if not name: raise SaltInvocationError('Must specify a KB "name"') if not source: raise SaltInvocationError('Must specify a "source" file to install') # Is the KB already installed if __salt__['wusa.is_installed'](name): ret['result'] = True ret['comment'] = '{0} already installed'.format(name) return ret # Check for test=True if __opts__['test'] is True: ret['result'] = None ret['comment'] = '{0} would be installed'.format(name) ret['result'] = None return ret # Cache the file cached_source_path = __salt__['cp.cache_file'](path=source, saltenv=__env__) if not cached_source_path: msg = 'Unable to cache {0} from saltenv "{1}"'.format( salt.utils.url.redact_http_basic_auth(source), __env__) ret['comment'] = msg return ret # Install the KB __salt__['wusa.install'](cached_source_path) # Verify successful install if __salt__['wusa.is_installed'](name): ret['comment'] = '{0} was installed'.format(name) ret['changes'] = {'old': False, 'new': True} ret['result'] = True else: ret['comment'] = '{0} failed to install'.format(name) return ret
python
def installed(name, source): ''' Ensure an update is installed on the minion Args: name(str): Name of the Windows KB ("KB123456") source (str): Source of .msu file corresponding to the KB Example: .. code-block:: yaml KB123456: wusa.installed: - source: salt://kb123456.msu ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Input validation if not name: raise SaltInvocationError('Must specify a KB "name"') if not source: raise SaltInvocationError('Must specify a "source" file to install') # Is the KB already installed if __salt__['wusa.is_installed'](name): ret['result'] = True ret['comment'] = '{0} already installed'.format(name) return ret # Check for test=True if __opts__['test'] is True: ret['result'] = None ret['comment'] = '{0} would be installed'.format(name) ret['result'] = None return ret # Cache the file cached_source_path = __salt__['cp.cache_file'](path=source, saltenv=__env__) if not cached_source_path: msg = 'Unable to cache {0} from saltenv "{1}"'.format( salt.utils.url.redact_http_basic_auth(source), __env__) ret['comment'] = msg return ret # Install the KB __salt__['wusa.install'](cached_source_path) # Verify successful install if __salt__['wusa.is_installed'](name): ret['comment'] = '{0} was installed'.format(name) ret['changes'] = {'old': False, 'new': True} ret['result'] = True else: ret['comment'] = '{0} failed to install'.format(name) return ret
[ "def", "installed", "(", "name", ",", "source", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "# Input validation", "if", "not", "name", ":", "raise...
Ensure an update is installed on the minion Args: name(str): Name of the Windows KB ("KB123456") source (str): Source of .msu file corresponding to the KB Example: .. code-block:: yaml KB123456: wusa.installed: - source: salt://kb123456.msu
[ "Ensure", "an", "update", "is", "installed", "on", "the", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_wusa.py#L37-L100
train
saltstack/salt
salt/states/win_wusa.py
uninstalled
def uninstalled(name): ''' Ensure an update is uninstalled from the minion Args: name(str): Name of the Windows KB ("KB123456") Example: .. code-block:: yaml KB123456: wusa.uninstalled ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Is the KB already uninstalled if not __salt__['wusa.is_installed'](name): ret['result'] = True ret['comment'] = '{0} already uninstalled'.format(name) return ret # Check for test=True if __opts__['test'] is True: ret['result'] = None ret['comment'] = '{0} would be uninstalled'.format(name) ret['result'] = None return ret # Uninstall the KB __salt__['wusa.uninstall'](name) # Verify successful uninstall if not __salt__['wusa.is_installed'](name): ret['comment'] = '{0} was uninstalled'.format(name) ret['changes'] = {'old': True, 'new': False} ret['result'] = True else: ret['comment'] = '{0} failed to uninstall'.format(name) return ret
python
def uninstalled(name): ''' Ensure an update is uninstalled from the minion Args: name(str): Name of the Windows KB ("KB123456") Example: .. code-block:: yaml KB123456: wusa.uninstalled ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Is the KB already uninstalled if not __salt__['wusa.is_installed'](name): ret['result'] = True ret['comment'] = '{0} already uninstalled'.format(name) return ret # Check for test=True if __opts__['test'] is True: ret['result'] = None ret['comment'] = '{0} would be uninstalled'.format(name) ret['result'] = None return ret # Uninstall the KB __salt__['wusa.uninstall'](name) # Verify successful uninstall if not __salt__['wusa.is_installed'](name): ret['comment'] = '{0} was uninstalled'.format(name) ret['changes'] = {'old': True, 'new': False} ret['result'] = True else: ret['comment'] = '{0} failed to uninstall'.format(name) return ret
[ "def", "uninstalled", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "# Is the KB already uninstalled", "if", "not", "__salt__", "[", "'wusa...
Ensure an update is uninstalled from the minion Args: name(str): Name of the Windows KB ("KB123456") Example: .. code-block:: yaml KB123456: wusa.uninstalled
[ "Ensure", "an", "update", "is", "uninstalled", "from", "the", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_wusa.py#L103-L148
train
saltstack/salt
salt/utils/smtp.py
send
def send(kwargs, opts): ''' Send an email with the data ''' opt_keys = ( 'smtp.to', 'smtp.from', 'smtp.host', 'smtp.port', 'smtp.tls', 'smtp.username', 'smtp.password', 'smtp.subject', 'smtp.gpgowner', 'smtp.content', ) config = {} for key in opt_keys: config[key] = opts.get(key, '') config.update(kwargs) if not config['smtp.port']: config['smtp.port'] = 25 log.debug('SMTP port has been set to %s', config['smtp.port']) log.debug("smtp_return: Subject is '%s'", config['smtp.subject']) if HAS_GNUPG and config['smtp.gpgowner']: gpg = gnupg.GPG( gnupghome=os.path.expanduser( '~{0}/.gnupg'.format(config['smtp.gpgowner']) ), options=['--trust-model always'] ) encrypted_data = gpg.encrypt(config['smtp.content'], config['smtp.to']) if encrypted_data.ok: log.debug('smtp_return: Encryption successful') config['smtp.content'] = six.text_type(encrypted_data) else: log.error( 'SMTP: Encryption failed, only an error message will be sent' ) config['smtp.content'] = ( 'Encryption failed, the return data was not sent.' '\r\n\r\n{0}\r\n{1}' ).format(encrypted_data.status, encrypted_data.stderr) message = ( 'From: {0}\r\n' 'To: {1}\r\n' 'Date: {2}\r\n' 'Subject: {3}\r\n' '\r\n' '{4}' ).format( config['smtp.from'], config['smtp.to'], formatdate(localtime=True), config['smtp.subject'], config['smtp.content'], ) log.debug('smtp_return: Connecting to the server...') server = smtplib.SMTP(config['smtp.host'], int(config['smtp.port'])) if config['smtp.tls'] is True: server.starttls() log.debug('smtp_return: TLS enabled') if config['smtp.username'] and config['smtp.password']: server.login(config['smtp.username'], config['smtp.password']) log.debug('smtp_return: Authenticated') server.sendmail(config['smtp.from'], config['smtp.to'], message) log.debug('smtp_return: Message sent.') server.quit()
python
def send(kwargs, opts): ''' Send an email with the data ''' opt_keys = ( 'smtp.to', 'smtp.from', 'smtp.host', 'smtp.port', 'smtp.tls', 'smtp.username', 'smtp.password', 'smtp.subject', 'smtp.gpgowner', 'smtp.content', ) config = {} for key in opt_keys: config[key] = opts.get(key, '') config.update(kwargs) if not config['smtp.port']: config['smtp.port'] = 25 log.debug('SMTP port has been set to %s', config['smtp.port']) log.debug("smtp_return: Subject is '%s'", config['smtp.subject']) if HAS_GNUPG and config['smtp.gpgowner']: gpg = gnupg.GPG( gnupghome=os.path.expanduser( '~{0}/.gnupg'.format(config['smtp.gpgowner']) ), options=['--trust-model always'] ) encrypted_data = gpg.encrypt(config['smtp.content'], config['smtp.to']) if encrypted_data.ok: log.debug('smtp_return: Encryption successful') config['smtp.content'] = six.text_type(encrypted_data) else: log.error( 'SMTP: Encryption failed, only an error message will be sent' ) config['smtp.content'] = ( 'Encryption failed, the return data was not sent.' '\r\n\r\n{0}\r\n{1}' ).format(encrypted_data.status, encrypted_data.stderr) message = ( 'From: {0}\r\n' 'To: {1}\r\n' 'Date: {2}\r\n' 'Subject: {3}\r\n' '\r\n' '{4}' ).format( config['smtp.from'], config['smtp.to'], formatdate(localtime=True), config['smtp.subject'], config['smtp.content'], ) log.debug('smtp_return: Connecting to the server...') server = smtplib.SMTP(config['smtp.host'], int(config['smtp.port'])) if config['smtp.tls'] is True: server.starttls() log.debug('smtp_return: TLS enabled') if config['smtp.username'] and config['smtp.password']: server.login(config['smtp.username'], config['smtp.password']) log.debug('smtp_return: Authenticated') server.sendmail(config['smtp.from'], config['smtp.to'], message) log.debug('smtp_return: Message sent.') server.quit()
[ "def", "send", "(", "kwargs", ",", "opts", ")", ":", "opt_keys", "=", "(", "'smtp.to'", ",", "'smtp.from'", ",", "'smtp.host'", ",", "'smtp.port'", ",", "'smtp.tls'", ",", "'smtp.username'", ",", "'smtp.password'", ",", "'smtp.subject'", ",", "'smtp.gpgowner'", ...
Send an email with the data
[ "Send", "an", "email", "with", "the", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/smtp.py#L50-L127
train
saltstack/salt
salt/modules/netaddress.py
list_cidr_ips
def list_cidr_ips(cidr): ''' Get a list of IP addresses from a CIDR. CLI example:: salt myminion netaddress.list_cidr_ips 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return [six.text_type(ip) for ip in list(ips)]
python
def list_cidr_ips(cidr): ''' Get a list of IP addresses from a CIDR. CLI example:: salt myminion netaddress.list_cidr_ips 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return [six.text_type(ip) for ip in list(ips)]
[ "def", "list_cidr_ips", "(", "cidr", ")", ":", "ips", "=", "netaddr", ".", "IPNetwork", "(", "cidr", ")", "return", "[", "six", ".", "text_type", "(", "ip", ")", "for", "ip", "in", "list", "(", "ips", ")", "]" ]
Get a list of IP addresses from a CIDR. CLI example:: salt myminion netaddress.list_cidr_ips 192.168.0.0/20
[ "Get", "a", "list", "of", "IP", "addresses", "from", "a", "CIDR", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netaddress.py#L35-L44
train
saltstack/salt
salt/modules/netaddress.py
list_cidr_ips_ipv6
def list_cidr_ips_ipv6(cidr): ''' Get a list of IPv6 addresses from a CIDR. CLI example:: salt myminion netaddress.list_cidr_ips_ipv6 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return [six.text_type(ip.ipv6()) for ip in list(ips)]
python
def list_cidr_ips_ipv6(cidr): ''' Get a list of IPv6 addresses from a CIDR. CLI example:: salt myminion netaddress.list_cidr_ips_ipv6 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return [six.text_type(ip.ipv6()) for ip in list(ips)]
[ "def", "list_cidr_ips_ipv6", "(", "cidr", ")", ":", "ips", "=", "netaddr", ".", "IPNetwork", "(", "cidr", ")", "return", "[", "six", ".", "text_type", "(", "ip", ".", "ipv6", "(", ")", ")", "for", "ip", "in", "list", "(", "ips", ")", "]" ]
Get a list of IPv6 addresses from a CIDR. CLI example:: salt myminion netaddress.list_cidr_ips_ipv6 192.168.0.0/20
[ "Get", "a", "list", "of", "IPv6", "addresses", "from", "a", "CIDR", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netaddress.py#L47-L56
train
saltstack/salt
salt/modules/netaddress.py
cidr_netmask
def cidr_netmask(cidr): ''' Get the netmask address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return six.text_type(ips.netmask)
python
def cidr_netmask(cidr): ''' Get the netmask address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return six.text_type(ips.netmask)
[ "def", "cidr_netmask", "(", "cidr", ")", ":", "ips", "=", "netaddr", ".", "IPNetwork", "(", "cidr", ")", "return", "six", ".", "text_type", "(", "ips", ".", "netmask", ")" ]
Get the netmask address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20
[ "Get", "the", "netmask", "address", "associated", "with", "a", "CIDR", "address", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netaddress.py#L59-L68
train
saltstack/salt
salt/modules/netaddress.py
cidr_broadcast
def cidr_broadcast(cidr): ''' Get the broadcast address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return six.text_type(ips.broadcast)
python
def cidr_broadcast(cidr): ''' Get the broadcast address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return six.text_type(ips.broadcast)
[ "def", "cidr_broadcast", "(", "cidr", ")", ":", "ips", "=", "netaddr", ".", "IPNetwork", "(", "cidr", ")", "return", "six", ".", "text_type", "(", "ips", ".", "broadcast", ")" ]
Get the broadcast address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20
[ "Get", "the", "broadcast", "address", "associated", "with", "a", "CIDR", "address", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netaddress.py#L71-L80
train
saltstack/salt
salt/modules/openstack_mng.py
restart_service
def restart_service(service_name, minimum_running_time=None): ''' Restart OpenStack service immediately, or only if it's running longer than specified value CLI Example: .. code-block:: bash salt '*' openstack_mng.restart_service neutron salt '*' openstack_mng.restart_service neutron minimum_running_time=600 ''' if minimum_running_time: ret_code = False # get system services list for interesting openstack service services = __salt__['cmd.run'](['/usr/bin/openstack-service', 'list', service_name]).split('\n') for service in services: service_info = __salt__['service.show'](service) with salt.utils.files.fopen('/proc/uptime') as rfh: boot_time = float( salt.utils.stringutils.to_unicode( rfh.read() ).split(' ')[0] ) expr_time = int(service_info.get('ExecMainStartTimestampMonotonic', 0)) / 1000000 < boot_time - minimum_running_time expr_active = service_info.get('ActiveState') == "active" if expr_time or not expr_active: # restart specific system service ret = __salt__['service.restart'](service) if ret: ret_code = True return ret_code else: # just restart os_cmd = ['/usr/bin/openstack-service', 'restart', service_name] return __salt__['cmd.retcode'](os_cmd) == 0
python
def restart_service(service_name, minimum_running_time=None): ''' Restart OpenStack service immediately, or only if it's running longer than specified value CLI Example: .. code-block:: bash salt '*' openstack_mng.restart_service neutron salt '*' openstack_mng.restart_service neutron minimum_running_time=600 ''' if minimum_running_time: ret_code = False # get system services list for interesting openstack service services = __salt__['cmd.run'](['/usr/bin/openstack-service', 'list', service_name]).split('\n') for service in services: service_info = __salt__['service.show'](service) with salt.utils.files.fopen('/proc/uptime') as rfh: boot_time = float( salt.utils.stringutils.to_unicode( rfh.read() ).split(' ')[0] ) expr_time = int(service_info.get('ExecMainStartTimestampMonotonic', 0)) / 1000000 < boot_time - minimum_running_time expr_active = service_info.get('ActiveState') == "active" if expr_time or not expr_active: # restart specific system service ret = __salt__['service.restart'](service) if ret: ret_code = True return ret_code else: # just restart os_cmd = ['/usr/bin/openstack-service', 'restart', service_name] return __salt__['cmd.retcode'](os_cmd) == 0
[ "def", "restart_service", "(", "service_name", ",", "minimum_running_time", "=", "None", ")", ":", "if", "minimum_running_time", ":", "ret_code", "=", "False", "# get system services list for interesting openstack service", "services", "=", "__salt__", "[", "'cmd.run'", "...
Restart OpenStack service immediately, or only if it's running longer than specified value CLI Example: .. code-block:: bash salt '*' openstack_mng.restart_service neutron salt '*' openstack_mng.restart_service neutron minimum_running_time=600
[ "Restart", "OpenStack", "service", "immediately", "or", "only", "if", "it", "s", "running", "longer", "than", "specified", "value" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openstack_mng.py#L65-L104
train
saltstack/salt
salt/returners/mysql.py
_get_options
def _get_options(ret=None): ''' Returns options used for the MySQL connection. ''' defaults = {'host': 'salt', 'user': 'salt', 'pass': 'salt', 'db': 'salt', 'port': 3306, 'ssl_ca': None, 'ssl_cert': None, 'ssl_key': None} attrs = {'host': 'host', 'user': 'user', 'pass': 'pass', 'db': 'db', 'port': 'port', 'ssl_ca': 'ssl_ca', 'ssl_cert': 'ssl_cert', 'ssl_key': 'ssl_key'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults) # post processing for k, v in six.iteritems(_options): if isinstance(v, six.string_types) and v.lower() == 'none': # Ensure 'None' is rendered as None _options[k] = None if k == 'port': # Ensure port is an int _options[k] = int(v) return _options
python
def _get_options(ret=None): ''' Returns options used for the MySQL connection. ''' defaults = {'host': 'salt', 'user': 'salt', 'pass': 'salt', 'db': 'salt', 'port': 3306, 'ssl_ca': None, 'ssl_cert': None, 'ssl_key': None} attrs = {'host': 'host', 'user': 'user', 'pass': 'pass', 'db': 'db', 'port': 'port', 'ssl_ca': 'ssl_ca', 'ssl_cert': 'ssl_cert', 'ssl_key': 'ssl_key'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults) # post processing for k, v in six.iteritems(_options): if isinstance(v, six.string_types) and v.lower() == 'none': # Ensure 'None' is rendered as None _options[k] = None if k == 'port': # Ensure port is an int _options[k] = int(v) return _options
[ "def", "_get_options", "(", "ret", "=", "None", ")", ":", "defaults", "=", "{", "'host'", ":", "'salt'", ",", "'user'", ":", "'salt'", ",", "'pass'", ":", "'salt'", ",", "'db'", ":", "'salt'", ",", "'port'", ":", "3306", ",", "'ssl_ca'", ":", "None",...
Returns options used for the MySQL connection.
[ "Returns", "options", "used", "for", "the", "MySQL", "connection", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L190-L227
train
saltstack/salt
salt/returners/mysql.py
_get_serv
def _get_serv(ret=None, commit=False): ''' Return a mysql cursor ''' _options = _get_options(ret) connect = True if __context__ and 'mysql_returner_conn' in __context__: try: log.debug('Trying to reuse MySQL connection pool') conn = __context__['mysql_returner_conn'] conn.ping() connect = False except OperationalError as exc: log.debug('OperationalError on ping: %s', exc) if connect: log.debug('Generating new MySQL connection pool') try: # An empty ssl_options dictionary passed to MySQLdb.connect will # effectively connect w/o SSL. ssl_options = {} if _options.get('ssl_ca'): ssl_options['ca'] = _options.get('ssl_ca') if _options.get('ssl_cert'): ssl_options['cert'] = _options.get('ssl_cert') if _options.get('ssl_key'): ssl_options['key'] = _options.get('ssl_key') conn = MySQLdb.connect(host=_options.get('host'), user=_options.get('user'), passwd=_options.get('pass'), db=_options.get('db'), port=_options.get('port'), ssl=ssl_options) try: __context__['mysql_returner_conn'] = conn except TypeError: pass except OperationalError as exc: raise salt.exceptions.SaltMasterError('MySQL returner could not connect to database: {exc}'.format(exc=exc)) cursor = conn.cursor() try: yield cursor except MySQLdb.DatabaseError as err: error = err.args sys.stderr.write(six.text_type(error)) cursor.execute("ROLLBACK") raise err else: if commit: cursor.execute("COMMIT") else: cursor.execute("ROLLBACK")
python
def _get_serv(ret=None, commit=False): ''' Return a mysql cursor ''' _options = _get_options(ret) connect = True if __context__ and 'mysql_returner_conn' in __context__: try: log.debug('Trying to reuse MySQL connection pool') conn = __context__['mysql_returner_conn'] conn.ping() connect = False except OperationalError as exc: log.debug('OperationalError on ping: %s', exc) if connect: log.debug('Generating new MySQL connection pool') try: # An empty ssl_options dictionary passed to MySQLdb.connect will # effectively connect w/o SSL. ssl_options = {} if _options.get('ssl_ca'): ssl_options['ca'] = _options.get('ssl_ca') if _options.get('ssl_cert'): ssl_options['cert'] = _options.get('ssl_cert') if _options.get('ssl_key'): ssl_options['key'] = _options.get('ssl_key') conn = MySQLdb.connect(host=_options.get('host'), user=_options.get('user'), passwd=_options.get('pass'), db=_options.get('db'), port=_options.get('port'), ssl=ssl_options) try: __context__['mysql_returner_conn'] = conn except TypeError: pass except OperationalError as exc: raise salt.exceptions.SaltMasterError('MySQL returner could not connect to database: {exc}'.format(exc=exc)) cursor = conn.cursor() try: yield cursor except MySQLdb.DatabaseError as err: error = err.args sys.stderr.write(six.text_type(error)) cursor.execute("ROLLBACK") raise err else: if commit: cursor.execute("COMMIT") else: cursor.execute("ROLLBACK")
[ "def", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "False", ")", ":", "_options", "=", "_get_options", "(", "ret", ")", "connect", "=", "True", "if", "__context__", "and", "'mysql_returner_conn'", "in", "__context__", ":", "try", ":", "log", ...
Return a mysql cursor
[ "Return", "a", "mysql", "cursor" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L231-L286
train
saltstack/salt
salt/returners/mysql.py
returner
def returner(ret): ''' Return data to a mysql server ''' # if a minion is returning a standalone job, get a jobid if ret['jid'] == 'req': ret['jid'] = prep_jid(nocache=ret.get('nocache', False)) save_load(ret['jid'], ret) try: with _get_serv(ret, commit=True) as cur: sql = '''INSERT INTO `salt_returns` (`fun`, `jid`, `return`, `id`, `success`, `full_ret`) VALUES (%s, %s, %s, %s, %s, %s)''' cur.execute(sql, (ret['fun'], ret['jid'], salt.utils.json.dumps(ret['return']), ret['id'], ret.get('success', False), salt.utils.json.dumps(ret))) except salt.exceptions.SaltMasterError as exc: log.critical(exc) log.critical('Could not store return with MySQL returner. MySQL server unavailable.')
python
def returner(ret): ''' Return data to a mysql server ''' # if a minion is returning a standalone job, get a jobid if ret['jid'] == 'req': ret['jid'] = prep_jid(nocache=ret.get('nocache', False)) save_load(ret['jid'], ret) try: with _get_serv(ret, commit=True) as cur: sql = '''INSERT INTO `salt_returns` (`fun`, `jid`, `return`, `id`, `success`, `full_ret`) VALUES (%s, %s, %s, %s, %s, %s)''' cur.execute(sql, (ret['fun'], ret['jid'], salt.utils.json.dumps(ret['return']), ret['id'], ret.get('success', False), salt.utils.json.dumps(ret))) except salt.exceptions.SaltMasterError as exc: log.critical(exc) log.critical('Could not store return with MySQL returner. MySQL server unavailable.')
[ "def", "returner", "(", "ret", ")", ":", "# if a minion is returning a standalone job, get a jobid", "if", "ret", "[", "'jid'", "]", "==", "'req'", ":", "ret", "[", "'jid'", "]", "=", "prep_jid", "(", "nocache", "=", "ret", ".", "get", "(", "'nocache'", ",",...
Return data to a mysql server
[ "Return", "data", "to", "a", "mysql", "server" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L289-L311
train
saltstack/salt
salt/returners/mysql.py
event_return
def event_return(events): ''' Return event to mysql server Requires that configuration be enabled via 'event_return' option in master config. ''' with _get_serv(events, commit=True) as cur: for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO `salt_events` (`tag`, `data`, `master_id`) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id']))
python
def event_return(events): ''' Return event to mysql server Requires that configuration be enabled via 'event_return' option in master config. ''' with _get_serv(events, commit=True) as cur: for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO `salt_events` (`tag`, `data`, `master_id`) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id']))
[ "def", "event_return", "(", "events", ")", ":", "with", "_get_serv", "(", "events", ",", "commit", "=", "True", ")", "as", "cur", ":", "for", "event", "in", "events", ":", "tag", "=", "event", ".", "get", "(", "'tag'", ",", "''", ")", "data", "=", ...
Return event to mysql server Requires that configuration be enabled via 'event_return' option in master config.
[ "Return", "event", "to", "mysql", "server" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L314-L327
train
saltstack/salt
salt/returners/mysql.py
save_load
def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' with _get_serv(commit=True) as cur: sql = '''INSERT INTO `jids` (`jid`, `load`) VALUES (%s, %s)''' try: cur.execute(sql, (jid, salt.utils.json.dumps(load))) except MySQLdb.IntegrityError: # https://github.com/saltstack/salt/issues/22171 # Without this try/except we get tons of duplicate entry errors # which result in job returns not being stored properly pass
python
def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' with _get_serv(commit=True) as cur: sql = '''INSERT INTO `jids` (`jid`, `load`) VALUES (%s, %s)''' try: cur.execute(sql, (jid, salt.utils.json.dumps(load))) except MySQLdb.IntegrityError: # https://github.com/saltstack/salt/issues/22171 # Without this try/except we get tons of duplicate entry errors # which result in job returns not being stored properly pass
[ "def", "save_load", "(", "jid", ",", "load", ",", "minions", "=", "None", ")", ":", "with", "_get_serv", "(", "commit", "=", "True", ")", "as", "cur", ":", "sql", "=", "'''INSERT INTO `jids` (`jid`, `load`) VALUES (%s, %s)'''", "try", ":", "cur", ".", "execu...
Save the load to the specified jid id
[ "Save", "the", "load", "to", "the", "specified", "jid", "id" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L330-L344
train
saltstack/salt
salt/returners/mysql.py
get_load
def get_load(jid): ''' Return the load data that marks a specified jid ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT `load` FROM `jids` WHERE `jid` = %s;''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return salt.utils.json.loads(data[0]) return {}
python
def get_load(jid): ''' Return the load data that marks a specified jid ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT `load` FROM `jids` WHERE `jid` = %s;''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return salt.utils.json.loads(data[0]) return {}
[ "def", "get_load", "(", "jid", ")", ":", "with", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "True", ")", "as", "cur", ":", "sql", "=", "'''SELECT `load` FROM `jids` WHERE `jid` = %s;'''", "cur", ".", "execute", "(", "sql", ",", "(", "jid", ...
Return the load data that marks a specified jid
[ "Return", "the", "load", "data", "that", "marks", "a", "specified", "jid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L354-L365
train
saltstack/salt
salt/returners/mysql.py
get_jid
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT id, full_ret FROM `salt_returns` WHERE `jid` = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret[minion] = salt.utils.json.loads(full_ret) return ret
python
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT id, full_ret FROM `salt_returns` WHERE `jid` = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret[minion] = salt.utils.json.loads(full_ret) return ret
[ "def", "get_jid", "(", "jid", ")", ":", "with", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "True", ")", "as", "cur", ":", "sql", "=", "'''SELECT id, full_ret FROM `salt_returns`\n WHERE `jid` = %s'''", "cur", ".", "execute", "(", "s...
Return the information returned when the specified job id was executed
[ "Return", "the", "information", "returned", "when", "the", "specified", "job", "id", "was", "executed" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L368-L383
train
saltstack/salt
salt/returners/mysql.py
get_fun
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT s.id,s.jid, s.full_ret FROM `salt_returns` s JOIN ( SELECT MAX(`jid`) as jid from `salt_returns` GROUP BY fun, id) max ON s.jid = max.jid WHERE s.fun = %s ''' cur.execute(sql, (fun,)) data = cur.fetchall() ret = {} if data: for minion, _, full_ret in data: ret[minion] = salt.utils.json.loads(full_ret) return ret
python
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT s.id,s.jid, s.full_ret FROM `salt_returns` s JOIN ( SELECT MAX(`jid`) as jid from `salt_returns` GROUP BY fun, id) max ON s.jid = max.jid WHERE s.fun = %s ''' cur.execute(sql, (fun,)) data = cur.fetchall() ret = {} if data: for minion, _, full_ret in data: ret[minion] = salt.utils.json.loads(full_ret) return ret
[ "def", "get_fun", "(", "fun", ")", ":", "with", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "True", ")", "as", "cur", ":", "sql", "=", "'''SELECT s.id,s.jid, s.full_ret\n FROM `salt_returns` s\n JOIN ( SELECT MAX(`jid`) as jid\n...
Return a dict of the last function called for all minions
[ "Return", "a", "dict", "of", "the", "last", "function", "called", "for", "all", "minions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L386-L407
train
saltstack/salt
salt/returners/mysql.py
get_jids_filter
def get_jids_filter(count, filter_find_job=True): ''' Return a list of all job ids :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT * FROM ( SELECT DISTINCT `jid` ,`load` FROM `jids` {0} ORDER BY `jid` DESC limit {1} ) `tmp` ORDER BY `jid`;''' where = '''WHERE `load` NOT LIKE '%"fun": "saltutil.find_job"%' ''' cur.execute(sql.format(where if filter_find_job else '', count)) data = cur.fetchall() ret = [] for jid in data: ret.append(salt.utils.jid.format_jid_instance_ext( jid[0], salt.utils.json.loads(jid[1]))) return ret
python
def get_jids_filter(count, filter_find_job=True): ''' Return a list of all job ids :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT * FROM ( SELECT DISTINCT `jid` ,`load` FROM `jids` {0} ORDER BY `jid` DESC limit {1} ) `tmp` ORDER BY `jid`;''' where = '''WHERE `load` NOT LIKE '%"fun": "saltutil.find_job"%' ''' cur.execute(sql.format(where if filter_find_job else '', count)) data = cur.fetchall() ret = [] for jid in data: ret.append(salt.utils.jid.format_jid_instance_ext( jid[0], salt.utils.json.loads(jid[1]))) return ret
[ "def", "get_jids_filter", "(", "count", ",", "filter_find_job", "=", "True", ")", ":", "with", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "True", ")", "as", "cur", ":", "sql", "=", "'''SELECT * FROM (\n SELECT DISTINCT `jid` ,`lo...
Return a list of all job ids :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs
[ "Return", "a", "list", "of", "all", "job", "ids", ":", "param", "int", "count", ":", "show", "not", "more", "than", "the", "count", "of", "most", "recent", "jobs", ":", "param", "bool", "filter_find_jobs", ":", "filter", "out", "saltutil", ".", "find_job...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L429-L452
train
saltstack/salt
salt/returners/mysql.py
get_minions
def get_minions(): ''' Return a list of minions ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT DISTINCT id FROM `salt_returns`''' cur.execute(sql) data = cur.fetchall() ret = [] for minion in data: ret.append(minion[0]) return ret
python
def get_minions(): ''' Return a list of minions ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT DISTINCT id FROM `salt_returns`''' cur.execute(sql) data = cur.fetchall() ret = [] for minion in data: ret.append(minion[0]) return ret
[ "def", "get_minions", "(", ")", ":", "with", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "True", ")", "as", "cur", ":", "sql", "=", "'''SELECT DISTINCT id\n FROM `salt_returns`'''", "cur", ".", "execute", "(", "sql", ")", "data", ...
Return a list of minions
[ "Return", "a", "list", "of", "minions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L455-L469
train
saltstack/salt
salt/returners/mysql.py
_purge_jobs
def _purge_jobs(timestamp): ''' Purge records from the returner tables. :param job_age_in_seconds: Purge jobs older than this :return: ''' with _get_serv() as cur: try: sql = 'delete from `jids` where jid in (select distinct jid from salt_returns where alter_time < %s)' cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to delete contents of table \'jids\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) try: sql = 'delete from `salt_returns` where alter_time < %s' cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to delete contents of table \'salt_returns\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) try: sql = 'delete from `salt_events` where alter_time < %s' cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to delete contents of table \'salt_events\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) return True
python
def _purge_jobs(timestamp): ''' Purge records from the returner tables. :param job_age_in_seconds: Purge jobs older than this :return: ''' with _get_serv() as cur: try: sql = 'delete from `jids` where jid in (select distinct jid from salt_returns where alter_time < %s)' cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to delete contents of table \'jids\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) try: sql = 'delete from `salt_returns` where alter_time < %s' cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to delete contents of table \'salt_returns\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) try: sql = 'delete from `salt_events` where alter_time < %s' cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to delete contents of table \'salt_events\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) return True
[ "def", "_purge_jobs", "(", "timestamp", ")", ":", "with", "_get_serv", "(", ")", "as", "cur", ":", "try", ":", "sql", "=", "'delete from `jids` where jid in (select distinct jid from salt_returns where alter_time < %s)'", "cur", ".", "execute", "(", "sql", ",", "(", ...
Purge records from the returner tables. :param job_age_in_seconds: Purge jobs older than this :return:
[ "Purge", "records", "from", "the", "returner", "tables", ".", ":", "param", "job_age_in_seconds", ":", "Purge", "jobs", "older", "than", "this", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L479-L513
train
saltstack/salt
salt/returners/mysql.py
_archive_jobs
def _archive_jobs(timestamp): ''' Copy rows to a set of backup tables, then purge rows. :param timestamp: Archive rows older than this timestamp :return: ''' source_tables = ['jids', 'salt_returns', 'salt_events'] with _get_serv() as cur: target_tables = {} for table_name in source_tables: try: tmp_table_name = table_name + '_archive' sql = 'create table if not exists {0} like {1}'.format(tmp_table_name, table_name) cur.execute(sql) cur.execute('COMMIT') target_tables[table_name] = tmp_table_name except MySQLdb.Error as e: log.error('mysql returner archiver was unable to create the archive tables.') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) try: sql = 'insert into `{0}` select * from `{1}` where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids') cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to copy contents of table \'jids\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) except Exception as e: log.error(e) raise try: sql = 'insert into `{0}` select * from `{1}` where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns') cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to copy contents of table \'salt_returns\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) try: sql = 'insert into `{0}` select * from `{1}` where alter_time < %s'.format(target_tables['salt_events'], 'salt_events') cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to copy contents of table \'salt_events\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) return _purge_jobs(timestamp)
python
def _archive_jobs(timestamp): ''' Copy rows to a set of backup tables, then purge rows. :param timestamp: Archive rows older than this timestamp :return: ''' source_tables = ['jids', 'salt_returns', 'salt_events'] with _get_serv() as cur: target_tables = {} for table_name in source_tables: try: tmp_table_name = table_name + '_archive' sql = 'create table if not exists {0} like {1}'.format(tmp_table_name, table_name) cur.execute(sql) cur.execute('COMMIT') target_tables[table_name] = tmp_table_name except MySQLdb.Error as e: log.error('mysql returner archiver was unable to create the archive tables.') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) try: sql = 'insert into `{0}` select * from `{1}` where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids') cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to copy contents of table \'jids\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) except Exception as e: log.error(e) raise try: sql = 'insert into `{0}` select * from `{1}` where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns') cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to copy contents of table \'salt_returns\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) try: sql = 'insert into `{0}` select * from `{1}` where alter_time < %s'.format(target_tables['salt_events'], 'salt_events') cur.execute(sql, (timestamp,)) cur.execute('COMMIT') except MySQLdb.Error as e: log.error('mysql returner archiver was unable to copy contents of table \'salt_events\'') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e)) return _purge_jobs(timestamp)
[ "def", "_archive_jobs", "(", "timestamp", ")", ":", "source_tables", "=", "[", "'jids'", ",", "'salt_returns'", ",", "'salt_events'", "]", "with", "_get_serv", "(", ")", "as", "cur", ":", "target_tables", "=", "{", "}", "for", "table_name", "in", "source_tab...
Copy rows to a set of backup tables, then purge rows. :param timestamp: Archive rows older than this timestamp :return:
[ "Copy", "rows", "to", "a", "set", "of", "backup", "tables", "then", "purge", "rows", ".", ":", "param", "timestamp", ":", "Archive", "rows", "older", "than", "this", "timestamp", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L516-L570
train
saltstack/salt
salt/returners/mysql.py
clean_old_jobs
def clean_old_jobs(): ''' Called in the master's event loop every loop_interval. Archives and/or deletes the events and job details from the database. :return: ''' if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0: try: with _get_serv() as cur: sql = 'select date_sub(now(), interval {0} hour) as stamp;'.format(__opts__['keep_jobs']) cur.execute(sql) rows = cur.fetchall() stamp = rows[0][0] if __opts__.get('archive_jobs', False): _archive_jobs(stamp) else: _purge_jobs(stamp) except MySQLdb.Error as e: log.error('Mysql returner was unable to get timestamp for purge/archive of jobs') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e))
python
def clean_old_jobs(): ''' Called in the master's event loop every loop_interval. Archives and/or deletes the events and job details from the database. :return: ''' if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0: try: with _get_serv() as cur: sql = 'select date_sub(now(), interval {0} hour) as stamp;'.format(__opts__['keep_jobs']) cur.execute(sql) rows = cur.fetchall() stamp = rows[0][0] if __opts__.get('archive_jobs', False): _archive_jobs(stamp) else: _purge_jobs(stamp) except MySQLdb.Error as e: log.error('Mysql returner was unable to get timestamp for purge/archive of jobs') log.error(six.text_type(e)) raise salt.exceptions.SaltRunnerError(six.text_type(e))
[ "def", "clean_old_jobs", "(", ")", ":", "if", "__opts__", ".", "get", "(", "'keep_jobs'", ",", "False", ")", "and", "int", "(", "__opts__", ".", "get", "(", "'keep_jobs'", ",", "0", ")", ")", ">", "0", ":", "try", ":", "with", "_get_serv", "(", ")"...
Called in the master's event loop every loop_interval. Archives and/or deletes the events and job details from the database. :return:
[ "Called", "in", "the", "master", "s", "event", "loop", "every", "loop_interval", ".", "Archives", "and", "/", "or", "deletes", "the", "events", "and", "job", "details", "from", "the", "database", ".", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mysql.py#L573-L594
train
saltstack/salt
salt/returners/syslog_return.py
_verify_options
def _verify_options(options): ''' Verify options and log warnings Returns True if all options can be verified, otherwise False ''' # sanity check all vals used for bitwise operations later bitwise_args = [('level', options['level']), ('facility', options['facility']) ] bitwise_args.extend([('option', x) for x in options['options']]) for opt_name, opt in bitwise_args: if not hasattr(syslog, opt): log.error('syslog has no attribute %s', opt) return False if not isinstance(getattr(syslog, opt), int): log.error('%s is not a valid syslog %s', opt, opt_name) return False # Sanity check tag if 'tag' in options: if not isinstance(options['tag'], six.string_types): log.error('tag must be a string') return False if len(options['tag']) > 32: log.error('tag size is limited to 32 characters') return False return True
python
def _verify_options(options): ''' Verify options and log warnings Returns True if all options can be verified, otherwise False ''' # sanity check all vals used for bitwise operations later bitwise_args = [('level', options['level']), ('facility', options['facility']) ] bitwise_args.extend([('option', x) for x in options['options']]) for opt_name, opt in bitwise_args: if not hasattr(syslog, opt): log.error('syslog has no attribute %s', opt) return False if not isinstance(getattr(syslog, opt), int): log.error('%s is not a valid syslog %s', opt, opt_name) return False # Sanity check tag if 'tag' in options: if not isinstance(options['tag'], six.string_types): log.error('tag must be a string') return False if len(options['tag']) > 32: log.error('tag size is limited to 32 characters') return False return True
[ "def", "_verify_options", "(", "options", ")", ":", "# sanity check all vals used for bitwise operations later", "bitwise_args", "=", "[", "(", "'level'", ",", "options", "[", "'level'", "]", ")", ",", "(", "'facility'", ",", "options", "[", "'facility'", "]", ")"...
Verify options and log warnings Returns True if all options can be verified, otherwise False
[ "Verify", "options", "and", "log", "warnings" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/syslog_return.py#L135-L166
train
saltstack/salt
salt/returners/syslog_return.py
returner
def returner(ret): ''' Return data to the local syslog ''' _options = _get_options(ret) if not _verify_options(_options): return # Get values from syslog module level = getattr(syslog, _options['level']) facility = getattr(syslog, _options['facility']) # parse for syslog options logoption = 0 for opt in _options['options']: logoption = logoption | getattr(syslog, opt) # Open syslog correctly based on options and tag if 'tag' in _options: syslog.openlog(ident=salt.utils.stringutils.to_str(_options['tag']), logoption=logoption) else: syslog.openlog(logoption=logoption) # Send log of given level and facility syslog.syslog(facility | level, salt.utils.json.dumps(ret)) # Close up to reset syslog to defaults syslog.closelog()
python
def returner(ret): ''' Return data to the local syslog ''' _options = _get_options(ret) if not _verify_options(_options): return # Get values from syslog module level = getattr(syslog, _options['level']) facility = getattr(syslog, _options['facility']) # parse for syslog options logoption = 0 for opt in _options['options']: logoption = logoption | getattr(syslog, opt) # Open syslog correctly based on options and tag if 'tag' in _options: syslog.openlog(ident=salt.utils.stringutils.to_str(_options['tag']), logoption=logoption) else: syslog.openlog(logoption=logoption) # Send log of given level and facility syslog.syslog(facility | level, salt.utils.json.dumps(ret)) # Close up to reset syslog to defaults syslog.closelog()
[ "def", "returner", "(", "ret", ")", ":", "_options", "=", "_get_options", "(", "ret", ")", "if", "not", "_verify_options", "(", "_options", ")", ":", "return", "# Get values from syslog module", "level", "=", "getattr", "(", "syslog", ",", "_options", "[", "...
Return data to the local syslog
[ "Return", "data", "to", "the", "local", "syslog" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/syslog_return.py#L175-L204
train
saltstack/salt
salt/utils/parsers.py
OptionParser.error
def error(self, msg): ''' error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. This keeps option parsing exit status uniform for all parsing errors. ''' self.print_usage(sys.stderr) self.exit(salt.defaults.exitcodes.EX_USAGE, '{0}: error: {1}\n'.format(self.get_prog_name(), msg))
python
def error(self, msg): ''' error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. This keeps option parsing exit status uniform for all parsing errors. ''' self.print_usage(sys.stderr) self.exit(salt.defaults.exitcodes.EX_USAGE, '{0}: error: {1}\n'.format(self.get_prog_name(), msg))
[ "def", "error", "(", "self", ",", "msg", ")", ":", "self", ".", "print_usage", "(", "sys", ".", "stderr", ")", "self", ".", "exit", "(", "salt", ".", "defaults", ".", "exitcodes", ".", "EX_USAGE", ",", "'{0}: error: {1}\\n'", ".", "format", "(", "self"...
error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. This keeps option parsing exit status uniform for all parsing errors.
[ "error", "(", "msg", ":", "string", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/parsers.py#L279-L287
train
saltstack/salt
salt/utils/parsers.py
DaemonMixIn.check_running
def check_running(self): ''' Check if a pid file exists and if it is associated with a running process. ''' if self.check_pidfile(): pid = self.get_pidfile() if not salt.utils.platform.is_windows(): if self.check_pidfile() and self.is_daemonized(pid) and os.getppid() != pid: return True else: # We have no os.getppid() on Windows. Use salt.utils.win_functions.get_parent_pid if self.check_pidfile() and self.is_daemonized(pid) and salt.utils.win_functions.get_parent_pid() != pid: return True return False
python
def check_running(self): ''' Check if a pid file exists and if it is associated with a running process. ''' if self.check_pidfile(): pid = self.get_pidfile() if not salt.utils.platform.is_windows(): if self.check_pidfile() and self.is_daemonized(pid) and os.getppid() != pid: return True else: # We have no os.getppid() on Windows. Use salt.utils.win_functions.get_parent_pid if self.check_pidfile() and self.is_daemonized(pid) and salt.utils.win_functions.get_parent_pid() != pid: return True return False
[ "def", "check_running", "(", "self", ")", ":", "if", "self", ".", "check_pidfile", "(", ")", ":", "pid", "=", "self", ".", "get_pidfile", "(", ")", "if", "not", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")", ":", "if", "self", ...
Check if a pid file exists and if it is associated with a running process.
[ "Check", "if", "a", "pid", "file", "exists", "and", "if", "it", "is", "associated", "with", "a", "running", "process", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/parsers.py#L1045-L1060
train
saltstack/salt
salt/utils/parsers.py
SaltSupportOptionParser.find_existing_configs
def find_existing_configs(self, default): ''' Find configuration files on the system. :return: ''' configs = [] for cfg in [default, self._config_filename_, 'minion', 'proxy', 'cloud', 'spm']: if not cfg: continue config_path = self.get_config_file_path(cfg) if os.path.exists(config_path): configs.append(cfg) if default and default not in configs: raise SystemExit('Unknown configuration unit: {}'.format(default)) return configs
python
def find_existing_configs(self, default): ''' Find configuration files on the system. :return: ''' configs = [] for cfg in [default, self._config_filename_, 'minion', 'proxy', 'cloud', 'spm']: if not cfg: continue config_path = self.get_config_file_path(cfg) if os.path.exists(config_path): configs.append(cfg) if default and default not in configs: raise SystemExit('Unknown configuration unit: {}'.format(default)) return configs
[ "def", "find_existing_configs", "(", "self", ",", "default", ")", ":", "configs", "=", "[", "]", "for", "cfg", "in", "[", "default", ",", "self", ".", "_config_filename_", ",", "'minion'", ",", "'proxy'", ",", "'cloud'", ",", "'spm'", "]", ":", "if", "...
Find configuration files on the system. :return:
[ "Find", "configuration", "files", "on", "the", "system", ".", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/parsers.py#L1950-L1966
train
saltstack/salt
salt/utils/parsers.py
SaltSupportOptionParser.setup_config
def setup_config(self, cfg=None): ''' Open suitable config file. :return: ''' _opts, _args = optparse.OptionParser.parse_args(self) configs = self.find_existing_configs(_opts.support_unit) if configs and cfg not in configs: cfg = configs[0] return config.master_config(self.get_config_file_path(cfg))
python
def setup_config(self, cfg=None): ''' Open suitable config file. :return: ''' _opts, _args = optparse.OptionParser.parse_args(self) configs = self.find_existing_configs(_opts.support_unit) if configs and cfg not in configs: cfg = configs[0] return config.master_config(self.get_config_file_path(cfg))
[ "def", "setup_config", "(", "self", ",", "cfg", "=", "None", ")", ":", "_opts", ",", "_args", "=", "optparse", ".", "OptionParser", ".", "parse_args", "(", "self", ")", "configs", "=", "self", ".", "find_existing_configs", "(", "_opts", ".", "support_unit"...
Open suitable config file. :return:
[ "Open", "suitable", "config", "file", ".", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/parsers.py#L1968-L1978
train
saltstack/salt
salt/states/ethtool.py
coalesce
def coalesce(name, **kwargs): ''' Manage coalescing settings of network device name Interface name to apply coalescing settings .. code-block:: yaml eth0: ethtool.coalesce: - name: eth0 - adaptive_rx: on - adaptive_tx: on - rx_usecs: 24 - rx_frame: 0 - rx_usecs_irq: 0 - rx_frames_irq: 0 - tx_usecs: 48 - tx_frames: 0 - tx_usecs_irq: 0 - tx_frames_irq: 0 - stats_block_usecs: 0 - pkt_rate_low: 0 - rx_usecs_low: 0 - rx_frames_low: 0 - tx_usecs_low: 0 - tx_frames_low: 0 - pkt_rate_high: 0 - rx_usecs_high: 0 - rx_frames_high: 0 - tx_usecs_high: 0 - tx_frames_high: 0 - sample_interval: 0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': 'Network device {0} coalescing settings are up to date.'.format(name), } apply_coalescing = False if 'test' not in kwargs: kwargs['test'] = __opts__.get('test', False) # Build coalescing settings try: old = __salt__['ethtool.show_coalesce'](name) if not isinstance(old, dict): ret['result'] = False ret['comment'] = 'Device {0} coalescing settings are not supported'.format(name) return ret new = {} diff = [] # Retreive changes to made for key, value in kwargs.items(): if key in old and value != old[key]: new.update({key: value}) diff.append('{0}: {1}'.format(key, value)) # Dry run if kwargs['test']: if not new: return ret if new: ret['result'] = None ret['comment'] = 'Device {0} coalescing settings are set to be ' \ 'updated:\n{1}'.format(name, '\n'.join(diff)) return ret # Prepare return output if new: apply_coalescing = True ret['comment'] = 'Device {0} coalescing settings updated.'.format(name) ret['changes']['ethtool_coalesce'] = '\n'.join(diff) except AttributeError as error: ret['result'] = False ret['comment'] = six.text_type(error) return ret # Apply coalescing settings if apply_coalescing: try: __salt__['ethtool.set_coalesce'](name, **new) except AttributeError as error: ret['result'] = False ret['comment'] = six.text_type(error) return ret return ret
python
def coalesce(name, **kwargs): ''' Manage coalescing settings of network device name Interface name to apply coalescing settings .. code-block:: yaml eth0: ethtool.coalesce: - name: eth0 - adaptive_rx: on - adaptive_tx: on - rx_usecs: 24 - rx_frame: 0 - rx_usecs_irq: 0 - rx_frames_irq: 0 - tx_usecs: 48 - tx_frames: 0 - tx_usecs_irq: 0 - tx_frames_irq: 0 - stats_block_usecs: 0 - pkt_rate_low: 0 - rx_usecs_low: 0 - rx_frames_low: 0 - tx_usecs_low: 0 - tx_frames_low: 0 - pkt_rate_high: 0 - rx_usecs_high: 0 - rx_frames_high: 0 - tx_usecs_high: 0 - tx_frames_high: 0 - sample_interval: 0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': 'Network device {0} coalescing settings are up to date.'.format(name), } apply_coalescing = False if 'test' not in kwargs: kwargs['test'] = __opts__.get('test', False) # Build coalescing settings try: old = __salt__['ethtool.show_coalesce'](name) if not isinstance(old, dict): ret['result'] = False ret['comment'] = 'Device {0} coalescing settings are not supported'.format(name) return ret new = {} diff = [] # Retreive changes to made for key, value in kwargs.items(): if key in old and value != old[key]: new.update({key: value}) diff.append('{0}: {1}'.format(key, value)) # Dry run if kwargs['test']: if not new: return ret if new: ret['result'] = None ret['comment'] = 'Device {0} coalescing settings are set to be ' \ 'updated:\n{1}'.format(name, '\n'.join(diff)) return ret # Prepare return output if new: apply_coalescing = True ret['comment'] = 'Device {0} coalescing settings updated.'.format(name) ret['changes']['ethtool_coalesce'] = '\n'.join(diff) except AttributeError as error: ret['result'] = False ret['comment'] = six.text_type(error) return ret # Apply coalescing settings if apply_coalescing: try: __salt__['ethtool.set_coalesce'](name, **new) except AttributeError as error: ret['result'] = False ret['comment'] = six.text_type(error) return ret return ret
[ "def", "coalesce", "(", "name", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "'Network device {0} coalescing settings are up to date.'", ".", ...
Manage coalescing settings of network device name Interface name to apply coalescing settings .. code-block:: yaml eth0: ethtool.coalesce: - name: eth0 - adaptive_rx: on - adaptive_tx: on - rx_usecs: 24 - rx_frame: 0 - rx_usecs_irq: 0 - rx_frames_irq: 0 - tx_usecs: 48 - tx_frames: 0 - tx_usecs_irq: 0 - tx_frames_irq: 0 - stats_block_usecs: 0 - pkt_rate_low: 0 - rx_usecs_low: 0 - rx_frames_low: 0 - tx_usecs_low: 0 - tx_frames_low: 0 - pkt_rate_high: 0 - rx_usecs_high: 0 - rx_frames_high: 0 - tx_usecs_high: 0 - tx_frames_high: 0 - sample_interval: 0
[ "Manage", "coalescing", "settings", "of", "network", "device" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ethtool.py#L51-L144
train
saltstack/salt
salt/states/esxdatacenter.py
datacenter_configured
def datacenter_configured(name): ''' Makes sure a datacenter exists. If the state is run by an ``esxdatacenter`` minion, the name of the datacenter is retrieved from the proxy details, otherwise the datacenter has the same name as the state. Supported proxies: esxdatacenter name: Datacenter name. Ignored if the proxytype is ``esxdatacenter``. ''' proxy_type = __salt__['vsphere.get_proxy_type']() if proxy_type == 'esxdatacenter': dc_name = __salt__['esxdatacenter.get_details']()['datacenter'] else: dc_name = name log.info('Running datacenter_configured for datacenter \'%s\'', dc_name) ret = {'name': name, 'changes': {}, 'result': None, 'comment': 'Default'} comments = [] si = None try: si = __salt__['vsphere.get_service_instance_via_proxy']() dcs = __salt__['vsphere.list_datacenters_via_proxy']( datacenter_names=[dc_name], service_instance=si) if not dcs: if __opts__['test']: comments.append('State will create ' 'datacenter \'{0}\'.'.format(dc_name)) else: log.debug('Creating datacenter \'%s\'', dc_name) __salt__['vsphere.create_datacenter'](dc_name, si) comments.append('Created datacenter \'{0}\'.'.format(dc_name)) log.info(comments[-1]) ret['changes'].update({'new': {'name': dc_name}}) else: comments.append('Datacenter \'{0}\' already exists. Nothing to be ' 'done.'.format(dc_name)) log.info(comments[-1]) __salt__['vsphere.disconnect'](si) ret['comment'] = '\n'.join(comments) ret['result'] = None if __opts__['test'] and ret['changes'] else True return ret except salt.exceptions.CommandExecutionError as exc: log.error('Error: %s', exc) if si: __salt__['vsphere.disconnect'](si) ret.update({ 'result': False if not __opts__['test'] else None, 'comment': six.text_type(exc)}) return ret
python
def datacenter_configured(name): ''' Makes sure a datacenter exists. If the state is run by an ``esxdatacenter`` minion, the name of the datacenter is retrieved from the proxy details, otherwise the datacenter has the same name as the state. Supported proxies: esxdatacenter name: Datacenter name. Ignored if the proxytype is ``esxdatacenter``. ''' proxy_type = __salt__['vsphere.get_proxy_type']() if proxy_type == 'esxdatacenter': dc_name = __salt__['esxdatacenter.get_details']()['datacenter'] else: dc_name = name log.info('Running datacenter_configured for datacenter \'%s\'', dc_name) ret = {'name': name, 'changes': {}, 'result': None, 'comment': 'Default'} comments = [] si = None try: si = __salt__['vsphere.get_service_instance_via_proxy']() dcs = __salt__['vsphere.list_datacenters_via_proxy']( datacenter_names=[dc_name], service_instance=si) if not dcs: if __opts__['test']: comments.append('State will create ' 'datacenter \'{0}\'.'.format(dc_name)) else: log.debug('Creating datacenter \'%s\'', dc_name) __salt__['vsphere.create_datacenter'](dc_name, si) comments.append('Created datacenter \'{0}\'.'.format(dc_name)) log.info(comments[-1]) ret['changes'].update({'new': {'name': dc_name}}) else: comments.append('Datacenter \'{0}\' already exists. Nothing to be ' 'done.'.format(dc_name)) log.info(comments[-1]) __salt__['vsphere.disconnect'](si) ret['comment'] = '\n'.join(comments) ret['result'] = None if __opts__['test'] and ret['changes'] else True return ret except salt.exceptions.CommandExecutionError as exc: log.error('Error: %s', exc) if si: __salt__['vsphere.disconnect'](si) ret.update({ 'result': False if not __opts__['test'] else None, 'comment': six.text_type(exc)}) return ret
[ "def", "datacenter_configured", "(", "name", ")", ":", "proxy_type", "=", "__salt__", "[", "'vsphere.get_proxy_type'", "]", "(", ")", "if", "proxy_type", "==", "'esxdatacenter'", ":", "dc_name", "=", "__salt__", "[", "'esxdatacenter.get_details'", "]", "(", ")", ...
Makes sure a datacenter exists. If the state is run by an ``esxdatacenter`` minion, the name of the datacenter is retrieved from the proxy details, otherwise the datacenter has the same name as the state. Supported proxies: esxdatacenter name: Datacenter name. Ignored if the proxytype is ``esxdatacenter``.
[ "Makes", "sure", "a", "datacenter", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxdatacenter.py#L72-L126
train
saltstack/salt
salt/modules/napalm_formula.py
_container_path
def _container_path(model, key=None, container=None, delim=DEFAULT_TARGET_DELIM): ''' Generate all the possible paths within an OpenConfig-like object. This function returns a generator. ''' if not key: key = '' if not container: container = 'config' for model_key, model_value in six.iteritems(model): if key: key_depth = '{prev_key}{delim}{cur_key}'.format(prev_key=key, delim=delim, cur_key=model_key) else: key_depth = model_key if model_key == container: yield key_depth else: for value in _container_path(model_value, key=key_depth, container=container, delim=delim): yield value
python
def _container_path(model, key=None, container=None, delim=DEFAULT_TARGET_DELIM): ''' Generate all the possible paths within an OpenConfig-like object. This function returns a generator. ''' if not key: key = '' if not container: container = 'config' for model_key, model_value in six.iteritems(model): if key: key_depth = '{prev_key}{delim}{cur_key}'.format(prev_key=key, delim=delim, cur_key=model_key) else: key_depth = model_key if model_key == container: yield key_depth else: for value in _container_path(model_value, key=key_depth, container=container, delim=delim): yield value
[ "def", "_container_path", "(", "model", ",", "key", "=", "None", ",", "container", "=", "None", ",", "delim", "=", "DEFAULT_TARGET_DELIM", ")", ":", "if", "not", "key", ":", "key", "=", "''", "if", "not", "container", ":", "container", "=", "'config'", ...
Generate all the possible paths within an OpenConfig-like object. This function returns a generator.
[ "Generate", "all", "the", "possible", "paths", "within", "an", "OpenConfig", "-", "like", "object", ".", "This", "function", "returns", "a", "generator", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_formula.py#L42-L68
train
saltstack/salt
salt/modules/napalm_formula.py
setval
def setval(key, val, dict_=None, delim=DEFAULT_TARGET_DELIM): ''' Set a value under the dictionary hierarchy identified under the key. The target 'foo/bar/baz' returns the dictionary hierarchy {'foo': {'bar': {'baz': {}}}}. .. note:: Currently this doesn't work with integers, i.e. cannot build lists dynamically. CLI Example: .. code-block:: bash salt '*' formula.setval foo:baz:bar True ''' if not dict_: dict_ = {} prev_hier = dict_ dict_hier = key.split(delim) for each in dict_hier[:-1]: if each not in prev_hier: prev_hier[each] = {} prev_hier = prev_hier[each] prev_hier[dict_hier[-1]] = copy.deepcopy(val) return dict_
python
def setval(key, val, dict_=None, delim=DEFAULT_TARGET_DELIM): ''' Set a value under the dictionary hierarchy identified under the key. The target 'foo/bar/baz' returns the dictionary hierarchy {'foo': {'bar': {'baz': {}}}}. .. note:: Currently this doesn't work with integers, i.e. cannot build lists dynamically. CLI Example: .. code-block:: bash salt '*' formula.setval foo:baz:bar True ''' if not dict_: dict_ = {} prev_hier = dict_ dict_hier = key.split(delim) for each in dict_hier[:-1]: if each not in prev_hier: prev_hier[each] = {} prev_hier = prev_hier[each] prev_hier[dict_hier[-1]] = copy.deepcopy(val) return dict_
[ "def", "setval", "(", "key", ",", "val", ",", "dict_", "=", "None", ",", "delim", "=", "DEFAULT_TARGET_DELIM", ")", ":", "if", "not", "dict_", ":", "dict_", "=", "{", "}", "prev_hier", "=", "dict_", "dict_hier", "=", "key", ".", "split", "(", "delim"...
Set a value under the dictionary hierarchy identified under the key. The target 'foo/bar/baz' returns the dictionary hierarchy {'foo': {'bar': {'baz': {}}}}. .. note:: Currently this doesn't work with integers, i.e. cannot build lists dynamically. CLI Example: .. code-block:: bash salt '*' formula.setval foo:baz:bar True
[ "Set", "a", "value", "under", "the", "dictionary", "hierarchy", "identified", "under", "the", "key", ".", "The", "target", "foo", "/", "bar", "/", "baz", "returns", "the", "dictionary", "hierarchy", "{", "foo", ":", "{", "bar", ":", "{", "baz", ":", "{...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_formula.py#L107-L133
train
saltstack/salt
salt/modules/napalm_formula.py
traverse
def traverse(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM): ''' Traverse a dict or list using a colon-delimited (or otherwise delimited, using the ``delimiter`` param) target string. The target ``foo:bar:0`` will return ``data['foo']['bar'][0]`` if this value exists, and will otherwise return the dict in the default argument. Function will automatically determine the target type. The target ``foo:bar:0`` will return data['foo']['bar'][0] if data like ``{'foo':{'bar':['baz']}}`` , if data like ``{'foo':{'bar':{'0':'baz'}}}`` then ``return data['foo']['bar']['0']`` CLI Example: .. code-block:: bash salt '*' napalm_formula.traverse "{'foo': {'bar': {'baz': True}}}" foo:baz:bar ''' return _traverse_dict_and_list(data, key, default=default, delimiter=delimiter)
python
def traverse(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM): ''' Traverse a dict or list using a colon-delimited (or otherwise delimited, using the ``delimiter`` param) target string. The target ``foo:bar:0`` will return ``data['foo']['bar'][0]`` if this value exists, and will otherwise return the dict in the default argument. Function will automatically determine the target type. The target ``foo:bar:0`` will return data['foo']['bar'][0] if data like ``{'foo':{'bar':['baz']}}`` , if data like ``{'foo':{'bar':{'0':'baz'}}}`` then ``return data['foo']['bar']['0']`` CLI Example: .. code-block:: bash salt '*' napalm_formula.traverse "{'foo': {'bar': {'baz': True}}}" foo:baz:bar ''' return _traverse_dict_and_list(data, key, default=default, delimiter=delimiter)
[ "def", "traverse", "(", "data", ",", "key", ",", "default", "=", "None", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ")", ":", "return", "_traverse_dict_and_list", "(", "data", ",", "key", ",", "default", "=", "default", ",", "delimiter", "=", "delimiter"...
Traverse a dict or list using a colon-delimited (or otherwise delimited, using the ``delimiter`` param) target string. The target ``foo:bar:0`` will return ``data['foo']['bar'][0]`` if this value exists, and will otherwise return the dict in the default argument. Function will automatically determine the target type. The target ``foo:bar:0`` will return data['foo']['bar'][0] if data like ``{'foo':{'bar':['baz']}}`` , if data like ``{'foo':{'bar':{'0':'baz'}}}`` then ``return data['foo']['bar']['0']`` CLI Example: .. code-block:: bash salt '*' napalm_formula.traverse "{'foo': {'bar': {'baz': True}}}" foo:baz:bar
[ "Traverse", "a", "dict", "or", "list", "using", "a", "colon", "-", "delimited", "(", "or", "otherwise", "delimited", "using", "the", "delimiter", "param", ")", "target", "string", ".", "The", "target", "foo", ":", "bar", ":", "0", "will", "return", "data...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_formula.py#L136-L153
train
saltstack/salt
salt/modules/napalm_formula.py
dictupdate
def dictupdate(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like ``FunctionWrapper``). If ``merge_lists=True``, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behaviour is only activated when ``recursive_update=True``. By default ``merge_lists=False``. ''' return salt.utils.dictupdate.update(dest, upd, recursive_update=recursive_update, merge_lists=merge_lists)
python
def dictupdate(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like ``FunctionWrapper``). If ``merge_lists=True``, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behaviour is only activated when ``recursive_update=True``. By default ``merge_lists=False``. ''' return salt.utils.dictupdate.update(dest, upd, recursive_update=recursive_update, merge_lists=merge_lists)
[ "def", "dictupdate", "(", "dest", ",", "upd", ",", "recursive_update", "=", "True", ",", "merge_lists", "=", "False", ")", ":", "return", "salt", ".", "utils", ".", "dictupdate", ".", "update", "(", "dest", ",", "upd", ",", "recursive_update", "=", "recu...
Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like ``FunctionWrapper``). If ``merge_lists=True``, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behaviour is only activated when ``recursive_update=True``. By default ``merge_lists=False``.
[ "Recursive", "version", "of", "the", "default", "dict", ".", "update" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_formula.py#L156-L170
train
saltstack/salt
salt/modules/napalm_formula.py
defaults
def defaults(model, defaults_, delim='//', flipped_merge=False): ''' Apply the defaults to a Python dictionary having the structure as described in the OpenConfig standards. model The OpenConfig model to apply the defaults to. defaults The dictionary of defaults. This argument must equally be structured with respect to the OpenConfig standards. For ease of use, the keys of these support glob matching, therefore we don't have to provide the defaults for each entity but only for the entity type. See an example below. delim: ``//`` The key delimiter to use. Generally, ``//`` should cover all the possible cases, and you don't need to override this value. flipped_merge: ``False`` Whether should merge the model into the defaults, or the defaults into the model. Default: ``False`` (merge the model into the defaults, i.e., any defaults would be overridden by the values from the ``model``). CLI Example: .. code-block:: bash salt '*' napalm_formula.defaults "{'interfaces': {'interface': {'Ethernet1': {'config': {'name': 'Ethernet1'}}}}}" "{'interfaces': {'interface': {'*': {'config': {'enabled': True}}}}}" As one can notice in the example above, the ``*`` corresponds to the interface name, therefore, the defaults will be applied on all the interfaces. ''' merged = {} log.debug('Applying the defaults:') log.debug(defaults_) log.debug('openconfig like dictionary:') log.debug(model) for model_path in _container_path(model, delim=delim): for default_path in _container_path(defaults_, delim=delim): log.debug('Comparing %s to %s', model_path, default_path) if not fnmatch.fnmatch(model_path, default_path) or\ not len(model_path.split(delim)) == len(default_path.split(delim)): continue log.debug('%s matches %s', model_path, default_path) # If there's a match, it will build the dictionary from the top devault_val = _traverse_dict_and_list(defaults_, default_path, delimiter=delim) merged = setval(model_path, devault_val, dict_=merged, delim=delim) log.debug('Complete default dictionary') log.debug(merged) log.debug('Merging with the model') log.debug(model) if flipped_merge: return salt.utils.dictupdate.update(model, merged) return salt.utils.dictupdate.update(merged, model)
python
def defaults(model, defaults_, delim='//', flipped_merge=False): ''' Apply the defaults to a Python dictionary having the structure as described in the OpenConfig standards. model The OpenConfig model to apply the defaults to. defaults The dictionary of defaults. This argument must equally be structured with respect to the OpenConfig standards. For ease of use, the keys of these support glob matching, therefore we don't have to provide the defaults for each entity but only for the entity type. See an example below. delim: ``//`` The key delimiter to use. Generally, ``//`` should cover all the possible cases, and you don't need to override this value. flipped_merge: ``False`` Whether should merge the model into the defaults, or the defaults into the model. Default: ``False`` (merge the model into the defaults, i.e., any defaults would be overridden by the values from the ``model``). CLI Example: .. code-block:: bash salt '*' napalm_formula.defaults "{'interfaces': {'interface': {'Ethernet1': {'config': {'name': 'Ethernet1'}}}}}" "{'interfaces': {'interface': {'*': {'config': {'enabled': True}}}}}" As one can notice in the example above, the ``*`` corresponds to the interface name, therefore, the defaults will be applied on all the interfaces. ''' merged = {} log.debug('Applying the defaults:') log.debug(defaults_) log.debug('openconfig like dictionary:') log.debug(model) for model_path in _container_path(model, delim=delim): for default_path in _container_path(defaults_, delim=delim): log.debug('Comparing %s to %s', model_path, default_path) if not fnmatch.fnmatch(model_path, default_path) or\ not len(model_path.split(delim)) == len(default_path.split(delim)): continue log.debug('%s matches %s', model_path, default_path) # If there's a match, it will build the dictionary from the top devault_val = _traverse_dict_and_list(defaults_, default_path, delimiter=delim) merged = setval(model_path, devault_val, dict_=merged, delim=delim) log.debug('Complete default dictionary') log.debug(merged) log.debug('Merging with the model') log.debug(model) if flipped_merge: return salt.utils.dictupdate.update(model, merged) return salt.utils.dictupdate.update(merged, model)
[ "def", "defaults", "(", "model", ",", "defaults_", ",", "delim", "=", "'//'", ",", "flipped_merge", "=", "False", ")", ":", "merged", "=", "{", "}", "log", ".", "debug", "(", "'Applying the defaults:'", ")", "log", ".", "debug", "(", "defaults_", ")", ...
Apply the defaults to a Python dictionary having the structure as described in the OpenConfig standards. model The OpenConfig model to apply the defaults to. defaults The dictionary of defaults. This argument must equally be structured with respect to the OpenConfig standards. For ease of use, the keys of these support glob matching, therefore we don't have to provide the defaults for each entity but only for the entity type. See an example below. delim: ``//`` The key delimiter to use. Generally, ``//`` should cover all the possible cases, and you don't need to override this value. flipped_merge: ``False`` Whether should merge the model into the defaults, or the defaults into the model. Default: ``False`` (merge the model into the defaults, i.e., any defaults would be overridden by the values from the ``model``). CLI Example: .. code-block:: bash salt '*' napalm_formula.defaults "{'interfaces': {'interface': {'Ethernet1': {'config': {'name': 'Ethernet1'}}}}}" "{'interfaces': {'interface': {'*': {'config': {'enabled': True}}}}}" As one can notice in the example above, the ``*`` corresponds to the interface name, therefore, the defaults will be applied on all the interfaces.
[ "Apply", "the", "defaults", "to", "a", "Python", "dictionary", "having", "the", "structure", "as", "described", "in", "the", "OpenConfig", "standards", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_formula.py#L173-L234
train
saltstack/salt
salt/modules/napalm_formula.py
render_field
def render_field(dictionary, field, prepend=None, append=None, quotes=False, **opts): ''' Render a field found under the ``field`` level of the hierarchy in the ``dictionary`` object. This is useful to render a field in a Jinja template without worrying that the hierarchy might not exist. For example if we do the following in Jinja: ``{{ interfaces.interface.Ethernet5.config.description }}`` for the following object: ``{'interfaces': {'interface': {'Ethernet1': {'config': {'enabled': True}}}}}`` it would error, as the ``Ethernet5`` key does not exist. With this helper, we can skip this and avoid existence checks. This must be however used with care. dictionary The dictionary to traverse. field The key name or part to traverse in the ``dictionary``. prepend: ``None`` The text to prepend in front of the text. Usually, we need to have the name of the field too when generating the configuration. append: ``None`` Text to append at the end. quotes: ``False`` Whether should wrap the text around quotes. CLI Example: .. code-block:: bash salt '*' napalm_formula.render_field "{'enabled': True}" enabled # This would return the value of the ``enabled`` leaf key salt '*' napalm_formula.render_field "{'enabled': True}" description # This would not error Jinja usage example: .. code-block:: jinja {%- set config = {'enabled': True, 'description': 'Interface description'} %} {{ salt.napalm_formula.render_field(config, 'description', quotes=True) }} The example above would be rendered on Arista / Cisco as: .. code-block:: text description "Interface description" While on Junos (the semicolon is important to be added, otherwise the configuration won't be accepted by Junos): .. code-block:: text description "Interface description"; ''' value = traverse(dictionary, field) if value is None: return '' if prepend is None: prepend = field.replace('_', '-') if append is None: if __grains__['os'] in ('junos',): append = ';' else: append = '' if quotes: value = '"{value}"'.format(value=value) return '{prepend} {value}{append}'.format(prepend=prepend, value=value, append=append)
python
def render_field(dictionary, field, prepend=None, append=None, quotes=False, **opts): ''' Render a field found under the ``field`` level of the hierarchy in the ``dictionary`` object. This is useful to render a field in a Jinja template without worrying that the hierarchy might not exist. For example if we do the following in Jinja: ``{{ interfaces.interface.Ethernet5.config.description }}`` for the following object: ``{'interfaces': {'interface': {'Ethernet1': {'config': {'enabled': True}}}}}`` it would error, as the ``Ethernet5`` key does not exist. With this helper, we can skip this and avoid existence checks. This must be however used with care. dictionary The dictionary to traverse. field The key name or part to traverse in the ``dictionary``. prepend: ``None`` The text to prepend in front of the text. Usually, we need to have the name of the field too when generating the configuration. append: ``None`` Text to append at the end. quotes: ``False`` Whether should wrap the text around quotes. CLI Example: .. code-block:: bash salt '*' napalm_formula.render_field "{'enabled': True}" enabled # This would return the value of the ``enabled`` leaf key salt '*' napalm_formula.render_field "{'enabled': True}" description # This would not error Jinja usage example: .. code-block:: jinja {%- set config = {'enabled': True, 'description': 'Interface description'} %} {{ salt.napalm_formula.render_field(config, 'description', quotes=True) }} The example above would be rendered on Arista / Cisco as: .. code-block:: text description "Interface description" While on Junos (the semicolon is important to be added, otherwise the configuration won't be accepted by Junos): .. code-block:: text description "Interface description"; ''' value = traverse(dictionary, field) if value is None: return '' if prepend is None: prepend = field.replace('_', '-') if append is None: if __grains__['os'] in ('junos',): append = ';' else: append = '' if quotes: value = '"{value}"'.format(value=value) return '{prepend} {value}{append}'.format(prepend=prepend, value=value, append=append)
[ "def", "render_field", "(", "dictionary", ",", "field", ",", "prepend", "=", "None", ",", "append", "=", "None", ",", "quotes", "=", "False", ",", "*", "*", "opts", ")", ":", "value", "=", "traverse", "(", "dictionary", ",", "field", ")", "if", "valu...
Render a field found under the ``field`` level of the hierarchy in the ``dictionary`` object. This is useful to render a field in a Jinja template without worrying that the hierarchy might not exist. For example if we do the following in Jinja: ``{{ interfaces.interface.Ethernet5.config.description }}`` for the following object: ``{'interfaces': {'interface': {'Ethernet1': {'config': {'enabled': True}}}}}`` it would error, as the ``Ethernet5`` key does not exist. With this helper, we can skip this and avoid existence checks. This must be however used with care. dictionary The dictionary to traverse. field The key name or part to traverse in the ``dictionary``. prepend: ``None`` The text to prepend in front of the text. Usually, we need to have the name of the field too when generating the configuration. append: ``None`` Text to append at the end. quotes: ``False`` Whether should wrap the text around quotes. CLI Example: .. code-block:: bash salt '*' napalm_formula.render_field "{'enabled': True}" enabled # This would return the value of the ``enabled`` leaf key salt '*' napalm_formula.render_field "{'enabled': True}" description # This would not error Jinja usage example: .. code-block:: jinja {%- set config = {'enabled': True, 'description': 'Interface description'} %} {{ salt.napalm_formula.render_field(config, 'description', quotes=True) }} The example above would be rendered on Arista / Cisco as: .. code-block:: text description "Interface description" While on Junos (the semicolon is important to be added, otherwise the configuration won't be accepted by Junos): .. code-block:: text description "Interface description";
[ "Render", "a", "field", "found", "under", "the", "field", "level", "of", "the", "hierarchy", "in", "the", "dictionary", "object", ".", "This", "is", "useful", "to", "render", "a", "field", "in", "a", "Jinja", "template", "without", "worrying", "that", "the...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_formula.py#L237-L314
train
saltstack/salt
salt/modules/napalm_formula.py
render_fields
def render_fields(dictionary, *fields, **opts): ''' This function works similarly to :mod:`render_field <salt.modules.napalm_formula.render_field>` but for a list of fields from the same dictionary, rendering, indenting and distributing them on separate lines. dictionary The dictionary to traverse. fields A list of field names or paths in the dictionary. indent: ``0`` The indentation to use, prepended to the rendered field. separator: ``\\n`` The separator to use between fields. CLI Example: .. code-block:: bash salt '*' napalm_formula.render_fields "{'mtu': 68, 'description': 'Interface description'}" mtu description Jinja usage example: .. code-block:: jinja {%- set config={'mtu': 68, 'description': 'Interface description'} %} {{ salt.napalm_formula.render_fields(config, 'mtu', 'description', quotes=True) }} The Jinja example above would generate the following configuration: .. code-block:: text mtu "68" description "Interface description" ''' results = [] for field in fields: res = render_field(dictionary, field, **opts) if res: results.append(res) if 'indent' not in opts: opts['indent'] = 0 if 'separator' not in opts: opts['separator'] = '\n{ind}'.format(ind=' '*opts['indent']) return opts['separator'].join(results)
python
def render_fields(dictionary, *fields, **opts): ''' This function works similarly to :mod:`render_field <salt.modules.napalm_formula.render_field>` but for a list of fields from the same dictionary, rendering, indenting and distributing them on separate lines. dictionary The dictionary to traverse. fields A list of field names or paths in the dictionary. indent: ``0`` The indentation to use, prepended to the rendered field. separator: ``\\n`` The separator to use between fields. CLI Example: .. code-block:: bash salt '*' napalm_formula.render_fields "{'mtu': 68, 'description': 'Interface description'}" mtu description Jinja usage example: .. code-block:: jinja {%- set config={'mtu': 68, 'description': 'Interface description'} %} {{ salt.napalm_formula.render_fields(config, 'mtu', 'description', quotes=True) }} The Jinja example above would generate the following configuration: .. code-block:: text mtu "68" description "Interface description" ''' results = [] for field in fields: res = render_field(dictionary, field, **opts) if res: results.append(res) if 'indent' not in opts: opts['indent'] = 0 if 'separator' not in opts: opts['separator'] = '\n{ind}'.format(ind=' '*opts['indent']) return opts['separator'].join(results)
[ "def", "render_fields", "(", "dictionary", ",", "*", "fields", ",", "*", "*", "opts", ")", ":", "results", "=", "[", "]", "for", "field", "in", "fields", ":", "res", "=", "render_field", "(", "dictionary", ",", "field", ",", "*", "*", "opts", ")", ...
This function works similarly to :mod:`render_field <salt.modules.napalm_formula.render_field>` but for a list of fields from the same dictionary, rendering, indenting and distributing them on separate lines. dictionary The dictionary to traverse. fields A list of field names or paths in the dictionary. indent: ``0`` The indentation to use, prepended to the rendered field. separator: ``\\n`` The separator to use between fields. CLI Example: .. code-block:: bash salt '*' napalm_formula.render_fields "{'mtu': 68, 'description': 'Interface description'}" mtu description Jinja usage example: .. code-block:: jinja {%- set config={'mtu': 68, 'description': 'Interface description'} %} {{ salt.napalm_formula.render_fields(config, 'mtu', 'description', quotes=True) }} The Jinja example above would generate the following configuration: .. code-block:: text mtu "68" description "Interface description"
[ "This", "function", "works", "similarly", "to", ":", "mod", ":", "render_field", "<salt", ".", "modules", ".", "napalm_formula", ".", "render_field", ">", "but", "for", "a", "list", "of", "fields", "from", "the", "same", "dictionary", "rendering", "indenting",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_formula.py#L317-L367
train
saltstack/salt
salt/states/win_servermanager.py
installed
def installed(name, features=None, recurse=False, restart=False, source=None, exclude=None): ''' Install the windows feature. To install a single feature, use the ``name`` parameter. To install multiple features, use the ``features`` parameter. .. note:: Some features require reboot after un/installation. If so, until the server is restarted other features can not be installed! Args: name (str): Short name of the feature (the right column in win_servermanager.list_available). This can be a single feature or a string of features in a comma delimited list (no spaces) .. note:: A list is not allowed in the name parameter of any state. Use the ``features`` parameter if you want to pass the features as a list features (Optional[list]): A list of features to install. If this is passed it will be used instead of the ``name`` parameter. .. versionadded:: 2018.3.0 recurse (Optional[bool]): Install all sub-features as well. If the feature is installed but one of its sub-features are not installed set this will install additional sub-features source (Optional[str]): Path to the source files if missing from the target system. None means that the system will use windows update services to find the required files. Default is None restart (Optional[bool]): Restarts the computer when installation is complete, if required by the role/feature installed. Default is False exclude (Optional[str]): The name of the feature to exclude when installing the named feature. This can be a single feature, a string of features in a comma-delimited list (no spaces), or a list of features. .. warning:: As there is no exclude option for the ``Add-WindowsFeature`` or ``Install-WindowsFeature`` PowerShell commands the features named in ``exclude`` will be installed with other sub-features and will then be removed. **If the feature named in ``exclude`` is not a sub-feature of one of the installed items it will still be removed.** Example: Do not use the role or feature names mentioned in the PKGMGR documentation. To get a list of available roles and features run the following command: .. code-block:: bash salt <minion_name> win_servermanager.list_available Use the name in the right column of the results. .. code-block:: yaml # Installs the IIS Web Server Role (Web-Server) IIS-WebServerRole: win_servermanager.installed: - recurse: True - name: Web-Server # Install multiple features, exclude the Web-Service install_multiple_features: win_servermanager.installed: - recurse: True - features: - RemoteAccess - XPS-Viewer - SNMP-Service - exclude: - Web-Server ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} # Check if features is not passed, use name. Split commas if features is None: features = name.split(',') # Make sure features is a list, split commas if not isinstance(features, list): features = features.split(',') # Determine if the feature is installed old = __salt__['win_servermanager.list_installed']() cur_feat = [] for feature in features: if feature not in old: ret['changes'][feature] = \ 'Will be installed recurse={0}'.format(recurse) elif recurse: ret['changes'][feature] = \ 'Already installed but might install sub-features' else: cur_feat.append(feature) if cur_feat: cur_feat.insert(0, 'The following features are already installed:') ret['comment'] = '\n- '.join(cur_feat) if not ret['changes']: return ret if __opts__['test']: ret['result'] = None return ret # Install the features status = __salt__['win_servermanager.install']( features, recurse=recurse, restart=restart, source=source, exclude=exclude) ret['result'] = status['Success'] # Show items failed to install fail_feat = [] new_feat = [] rem_feat = [] for feature in status['Features']: # Features that failed to install or be removed if not status['Features'][feature].get('Success', True): fail_feat.append('- {0}'.format(feature)) # Features that installed elif '(exclude)' not in status['Features'][feature]['Message']: new_feat.append('- {0}'.format(feature)) # Show items that were removed because they were part of `exclude` elif '(exclude)' in status['Features'][feature]['Message']: rem_feat.append('- {0}'.format(feature)) if fail_feat: fail_feat.insert(0, 'Failed to install the following:') if new_feat: new_feat.insert(0, 'Installed the following:') if rem_feat: rem_feat.insert(0, 'Removed the following (exclude):') ret['comment'] = '\n'.join(fail_feat + new_feat + rem_feat) # Get the changes new = __salt__['win_servermanager.list_installed']() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret
python
def installed(name, features=None, recurse=False, restart=False, source=None, exclude=None): ''' Install the windows feature. To install a single feature, use the ``name`` parameter. To install multiple features, use the ``features`` parameter. .. note:: Some features require reboot after un/installation. If so, until the server is restarted other features can not be installed! Args: name (str): Short name of the feature (the right column in win_servermanager.list_available). This can be a single feature or a string of features in a comma delimited list (no spaces) .. note:: A list is not allowed in the name parameter of any state. Use the ``features`` parameter if you want to pass the features as a list features (Optional[list]): A list of features to install. If this is passed it will be used instead of the ``name`` parameter. .. versionadded:: 2018.3.0 recurse (Optional[bool]): Install all sub-features as well. If the feature is installed but one of its sub-features are not installed set this will install additional sub-features source (Optional[str]): Path to the source files if missing from the target system. None means that the system will use windows update services to find the required files. Default is None restart (Optional[bool]): Restarts the computer when installation is complete, if required by the role/feature installed. Default is False exclude (Optional[str]): The name of the feature to exclude when installing the named feature. This can be a single feature, a string of features in a comma-delimited list (no spaces), or a list of features. .. warning:: As there is no exclude option for the ``Add-WindowsFeature`` or ``Install-WindowsFeature`` PowerShell commands the features named in ``exclude`` will be installed with other sub-features and will then be removed. **If the feature named in ``exclude`` is not a sub-feature of one of the installed items it will still be removed.** Example: Do not use the role or feature names mentioned in the PKGMGR documentation. To get a list of available roles and features run the following command: .. code-block:: bash salt <minion_name> win_servermanager.list_available Use the name in the right column of the results. .. code-block:: yaml # Installs the IIS Web Server Role (Web-Server) IIS-WebServerRole: win_servermanager.installed: - recurse: True - name: Web-Server # Install multiple features, exclude the Web-Service install_multiple_features: win_servermanager.installed: - recurse: True - features: - RemoteAccess - XPS-Viewer - SNMP-Service - exclude: - Web-Server ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} # Check if features is not passed, use name. Split commas if features is None: features = name.split(',') # Make sure features is a list, split commas if not isinstance(features, list): features = features.split(',') # Determine if the feature is installed old = __salt__['win_servermanager.list_installed']() cur_feat = [] for feature in features: if feature not in old: ret['changes'][feature] = \ 'Will be installed recurse={0}'.format(recurse) elif recurse: ret['changes'][feature] = \ 'Already installed but might install sub-features' else: cur_feat.append(feature) if cur_feat: cur_feat.insert(0, 'The following features are already installed:') ret['comment'] = '\n- '.join(cur_feat) if not ret['changes']: return ret if __opts__['test']: ret['result'] = None return ret # Install the features status = __salt__['win_servermanager.install']( features, recurse=recurse, restart=restart, source=source, exclude=exclude) ret['result'] = status['Success'] # Show items failed to install fail_feat = [] new_feat = [] rem_feat = [] for feature in status['Features']: # Features that failed to install or be removed if not status['Features'][feature].get('Success', True): fail_feat.append('- {0}'.format(feature)) # Features that installed elif '(exclude)' not in status['Features'][feature]['Message']: new_feat.append('- {0}'.format(feature)) # Show items that were removed because they were part of `exclude` elif '(exclude)' in status['Features'][feature]['Message']: rem_feat.append('- {0}'.format(feature)) if fail_feat: fail_feat.insert(0, 'Failed to install the following:') if new_feat: new_feat.insert(0, 'Installed the following:') if rem_feat: rem_feat.insert(0, 'Removed the following (exclude):') ret['comment'] = '\n'.join(fail_feat + new_feat + rem_feat) # Get the changes new = __salt__['win_servermanager.list_installed']() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret
[ "def", "installed", "(", "name", ",", "features", "=", "None", ",", "recurse", "=", "False", ",", "restart", "=", "False", ",", "source", "=", "None", ",", "exclude", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", "...
Install the windows feature. To install a single feature, use the ``name`` parameter. To install multiple features, use the ``features`` parameter. .. note:: Some features require reboot after un/installation. If so, until the server is restarted other features can not be installed! Args: name (str): Short name of the feature (the right column in win_servermanager.list_available). This can be a single feature or a string of features in a comma delimited list (no spaces) .. note:: A list is not allowed in the name parameter of any state. Use the ``features`` parameter if you want to pass the features as a list features (Optional[list]): A list of features to install. If this is passed it will be used instead of the ``name`` parameter. .. versionadded:: 2018.3.0 recurse (Optional[bool]): Install all sub-features as well. If the feature is installed but one of its sub-features are not installed set this will install additional sub-features source (Optional[str]): Path to the source files if missing from the target system. None means that the system will use windows update services to find the required files. Default is None restart (Optional[bool]): Restarts the computer when installation is complete, if required by the role/feature installed. Default is False exclude (Optional[str]): The name of the feature to exclude when installing the named feature. This can be a single feature, a string of features in a comma-delimited list (no spaces), or a list of features. .. warning:: As there is no exclude option for the ``Add-WindowsFeature`` or ``Install-WindowsFeature`` PowerShell commands the features named in ``exclude`` will be installed with other sub-features and will then be removed. **If the feature named in ``exclude`` is not a sub-feature of one of the installed items it will still be removed.** Example: Do not use the role or feature names mentioned in the PKGMGR documentation. To get a list of available roles and features run the following command: .. code-block:: bash salt <minion_name> win_servermanager.list_available Use the name in the right column of the results. .. code-block:: yaml # Installs the IIS Web Server Role (Web-Server) IIS-WebServerRole: win_servermanager.installed: - recurse: True - name: Web-Server # Install multiple features, exclude the Web-Service install_multiple_features: win_servermanager.installed: - recurse: True - features: - RemoteAccess - XPS-Viewer - SNMP-Service - exclude: - Web-Server
[ "Install", "the", "windows", "feature", ".", "To", "install", "a", "single", "feature", "use", "the", "name", "parameter", ".", "To", "install", "multiple", "features", "use", "the", "features", "parameter", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_servermanager.py#L25-L189
train
saltstack/salt
salt/states/win_servermanager.py
removed
def removed(name, features=None, remove_payload=False, restart=False): ''' Remove the windows feature To remove a single feature, use the ``name`` parameter. To remove multiple features, use the ``features`` parameter. Args: name (str): Short name of the feature (the right column in win_servermanager.list_available). This can be a single feature or a string of features in a comma-delimited list (no spaces) .. note:: A list is not allowed in the name parameter of any state. Use the ``features`` parameter if you want to pass the features as a list features (Optional[list]): A list of features to remove. If this is passed it will be used instead of the ``name`` parameter. .. versionadded:: 2018.3.0 remove_payload (Optional[bool]): True will cause the feature to be removed from the side-by-side store. To install the feature in the future you will need to specify the ``source`` restart (Optional[bool]): Restarts the computer when uninstall is complete if required by the role/feature uninstall. Default is False .. note:: Some features require a reboot after uninstall. If so the feature will not be completely uninstalled until the server is restarted. Example: Do not use the role or feature names mentioned in the PKGMGR documentation. To get a list of available roles and features run the following command: .. code-block:: bash salt <minion_name> win_servermanager.list_available Use the name in the right column of the results. .. code-block:: yaml # Uninstall the IIS Web Server Rol (Web-Server) IIS-WebserverRole: win_servermanager.removed: - name: Web-Server # Uninstall multiple features, reboot if required uninstall_multiple_features: win_servermanager.removed: - features: - RemoteAccess - XPX-Viewer - SNMP-Service - restart: True ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} # Check if features is not passed, use name. Split commas if features is None: features = name.split(',') # Make sure features is a list, split commas if not isinstance(features, list): features = features.split(',') # Determine if the feature is installed old = __salt__['win_servermanager.list_installed']() rem_feat = [] for feature in features: if feature in old: ret['changes'][feature] = 'Will be removed' else: rem_feat.append(feature) if rem_feat: rem_feat.insert(0, 'The following features are not installed:') ret['comment'] = '\n- '.join(rem_feat) if not ret['changes']: return ret if __opts__['test']: ret['result'] = None return ret # Remove the features status = __salt__['win_servermanager.remove']( features, remove_payload=remove_payload, restart=restart) ret['result'] = status['Success'] # Some items failed to uninstall fail_feat = [] rem_feat = [] for feature in status['Features']: # Use get because sometimes 'Success' isn't defined such as when the # feature is already uninstalled if not status['Features'][feature].get('Success', True): # Show items that failed to uninstall fail_feat.append('- {0}'.format(feature)) else: # Show items that uninstalled rem_feat.append('- {0}'.format(feature)) if fail_feat: fail_feat.insert(0, 'Failed to remove the following:') if rem_feat: rem_feat.insert(0, 'Removed the following:') ret['comment'] = '\n'.join(fail_feat + rem_feat) # Get the changes new = __salt__['win_servermanager.list_installed']() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret
python
def removed(name, features=None, remove_payload=False, restart=False): ''' Remove the windows feature To remove a single feature, use the ``name`` parameter. To remove multiple features, use the ``features`` parameter. Args: name (str): Short name of the feature (the right column in win_servermanager.list_available). This can be a single feature or a string of features in a comma-delimited list (no spaces) .. note:: A list is not allowed in the name parameter of any state. Use the ``features`` parameter if you want to pass the features as a list features (Optional[list]): A list of features to remove. If this is passed it will be used instead of the ``name`` parameter. .. versionadded:: 2018.3.0 remove_payload (Optional[bool]): True will cause the feature to be removed from the side-by-side store. To install the feature in the future you will need to specify the ``source`` restart (Optional[bool]): Restarts the computer when uninstall is complete if required by the role/feature uninstall. Default is False .. note:: Some features require a reboot after uninstall. If so the feature will not be completely uninstalled until the server is restarted. Example: Do not use the role or feature names mentioned in the PKGMGR documentation. To get a list of available roles and features run the following command: .. code-block:: bash salt <minion_name> win_servermanager.list_available Use the name in the right column of the results. .. code-block:: yaml # Uninstall the IIS Web Server Rol (Web-Server) IIS-WebserverRole: win_servermanager.removed: - name: Web-Server # Uninstall multiple features, reboot if required uninstall_multiple_features: win_servermanager.removed: - features: - RemoteAccess - XPX-Viewer - SNMP-Service - restart: True ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} # Check if features is not passed, use name. Split commas if features is None: features = name.split(',') # Make sure features is a list, split commas if not isinstance(features, list): features = features.split(',') # Determine if the feature is installed old = __salt__['win_servermanager.list_installed']() rem_feat = [] for feature in features: if feature in old: ret['changes'][feature] = 'Will be removed' else: rem_feat.append(feature) if rem_feat: rem_feat.insert(0, 'The following features are not installed:') ret['comment'] = '\n- '.join(rem_feat) if not ret['changes']: return ret if __opts__['test']: ret['result'] = None return ret # Remove the features status = __salt__['win_servermanager.remove']( features, remove_payload=remove_payload, restart=restart) ret['result'] = status['Success'] # Some items failed to uninstall fail_feat = [] rem_feat = [] for feature in status['Features']: # Use get because sometimes 'Success' isn't defined such as when the # feature is already uninstalled if not status['Features'][feature].get('Success', True): # Show items that failed to uninstall fail_feat.append('- {0}'.format(feature)) else: # Show items that uninstalled rem_feat.append('- {0}'.format(feature)) if fail_feat: fail_feat.insert(0, 'Failed to remove the following:') if rem_feat: rem_feat.insert(0, 'Removed the following:') ret['comment'] = '\n'.join(fail_feat + rem_feat) # Get the changes new = __salt__['win_servermanager.list_installed']() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret
[ "def", "removed", "(", "name", ",", "features", "=", "None", ",", "remove_payload", "=", "False", ",", "restart", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'...
Remove the windows feature To remove a single feature, use the ``name`` parameter. To remove multiple features, use the ``features`` parameter. Args: name (str): Short name of the feature (the right column in win_servermanager.list_available). This can be a single feature or a string of features in a comma-delimited list (no spaces) .. note:: A list is not allowed in the name parameter of any state. Use the ``features`` parameter if you want to pass the features as a list features (Optional[list]): A list of features to remove. If this is passed it will be used instead of the ``name`` parameter. .. versionadded:: 2018.3.0 remove_payload (Optional[bool]): True will cause the feature to be removed from the side-by-side store. To install the feature in the future you will need to specify the ``source`` restart (Optional[bool]): Restarts the computer when uninstall is complete if required by the role/feature uninstall. Default is False .. note:: Some features require a reboot after uninstall. If so the feature will not be completely uninstalled until the server is restarted. Example: Do not use the role or feature names mentioned in the PKGMGR documentation. To get a list of available roles and features run the following command: .. code-block:: bash salt <minion_name> win_servermanager.list_available Use the name in the right column of the results. .. code-block:: yaml # Uninstall the IIS Web Server Rol (Web-Server) IIS-WebserverRole: win_servermanager.removed: - name: Web-Server # Uninstall multiple features, reboot if required uninstall_multiple_features: win_servermanager.removed: - features: - RemoteAccess - XPX-Viewer - SNMP-Service - restart: True
[ "Remove", "the", "windows", "feature", "To", "remove", "a", "single", "feature", "use", "the", "name", "parameter", ".", "To", "remove", "multiple", "features", "use", "the", "features", "parameter", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_servermanager.py#L192-L320
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
_check_cors_origin
def _check_cors_origin(origin, allowed_origins): ''' Check if an origin match cors allowed origins ''' if isinstance(allowed_origins, list): if origin in allowed_origins: return origin elif allowed_origins == '*': return allowed_origins elif allowed_origins == origin: # Cors origin is either * or specific origin return allowed_origins
python
def _check_cors_origin(origin, allowed_origins): ''' Check if an origin match cors allowed origins ''' if isinstance(allowed_origins, list): if origin in allowed_origins: return origin elif allowed_origins == '*': return allowed_origins elif allowed_origins == origin: # Cors origin is either * or specific origin return allowed_origins
[ "def", "_check_cors_origin", "(", "origin", ",", "allowed_origins", ")", ":", "if", "isinstance", "(", "allowed_origins", ",", "list", ")", ":", "if", "origin", "in", "allowed_origins", ":", "return", "origin", "elif", "allowed_origins", "==", "'*'", ":", "ret...
Check if an origin match cors allowed origins
[ "Check", "if", "an", "origin", "match", "cors", "allowed", "origins" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1750-L1761
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
EventListener.clean_by_request
def clean_by_request(self, request): ''' Remove all futures that were waiting for request `request` since it is done waiting ''' if request not in self.request_map: return for tag, matcher, future in self.request_map[request]: # timeout the future self._timeout_future(tag, matcher, future) # remove the timeout if future in self.timeout_map: tornado.ioloop.IOLoop.current().remove_timeout(self.timeout_map[future]) del self.timeout_map[future] del self.request_map[request]
python
def clean_by_request(self, request): ''' Remove all futures that were waiting for request `request` since it is done waiting ''' if request not in self.request_map: return for tag, matcher, future in self.request_map[request]: # timeout the future self._timeout_future(tag, matcher, future) # remove the timeout if future in self.timeout_map: tornado.ioloop.IOLoop.current().remove_timeout(self.timeout_map[future]) del self.timeout_map[future] del self.request_map[request]
[ "def", "clean_by_request", "(", "self", ",", "request", ")", ":", "if", "request", "not", "in", "self", ".", "request_map", ":", "return", "for", "tag", ",", "matcher", ",", "future", "in", "self", ".", "request_map", "[", "request", "]", ":", "# timeout...
Remove all futures that were waiting for request `request` since it is done waiting
[ "Remove", "all", "futures", "that", "were", "waiting", "for", "request", "request", "since", "it", "is", "done", "waiting" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L302-L316
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
EventListener.get_event
def get_event(self, request, tag='', matcher=prefix_matcher.__func__, callback=None, timeout=None ): ''' Get an event (asynchronous of course) return a future that will get it later ''' # if the request finished, no reason to allow event fetching, since we # can't send back to the client if request._finished: future = Future() future.set_exception(TimeoutException()) return future future = Future() if callback is not None: def handle_future(future): tornado.ioloop.IOLoop.current().add_callback(callback, future) future.add_done_callback(handle_future) # add this tag and future to the callbacks self.tag_map[(tag, matcher)].append(future) self.request_map[request].append((tag, matcher, future)) if timeout: timeout_future = tornado.ioloop.IOLoop.current().call_later(timeout, self._timeout_future, tag, matcher, future) self.timeout_map[future] = timeout_future return future
python
def get_event(self, request, tag='', matcher=prefix_matcher.__func__, callback=None, timeout=None ): ''' Get an event (asynchronous of course) return a future that will get it later ''' # if the request finished, no reason to allow event fetching, since we # can't send back to the client if request._finished: future = Future() future.set_exception(TimeoutException()) return future future = Future() if callback is not None: def handle_future(future): tornado.ioloop.IOLoop.current().add_callback(callback, future) future.add_done_callback(handle_future) # add this tag and future to the callbacks self.tag_map[(tag, matcher)].append(future) self.request_map[request].append((tag, matcher, future)) if timeout: timeout_future = tornado.ioloop.IOLoop.current().call_later(timeout, self._timeout_future, tag, matcher, future) self.timeout_map[future] = timeout_future return future
[ "def", "get_event", "(", "self", ",", "request", ",", "tag", "=", "''", ",", "matcher", "=", "prefix_matcher", ".", "__func__", ",", "callback", "=", "None", ",", "timeout", "=", "None", ")", ":", "# if the request finished, no reason to allow event fetching, sinc...
Get an event (asynchronous of course) return a future that will get it later
[ "Get", "an", "event", "(", "asynchronous", "of", "course", ")", "return", "a", "future", "that", "will", "get", "it", "later" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L330-L360
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
EventListener._timeout_future
def _timeout_future(self, tag, matcher, future): ''' Timeout a specific future ''' if (tag, matcher) not in self.tag_map: return if not future.done(): future.set_exception(TimeoutException()) self.tag_map[(tag, matcher)].remove(future) if not self.tag_map[(tag, matcher)]: del self.tag_map[(tag, matcher)]
python
def _timeout_future(self, tag, matcher, future): ''' Timeout a specific future ''' if (tag, matcher) not in self.tag_map: return if not future.done(): future.set_exception(TimeoutException()) self.tag_map[(tag, matcher)].remove(future) if not self.tag_map[(tag, matcher)]: del self.tag_map[(tag, matcher)]
[ "def", "_timeout_future", "(", "self", ",", "tag", ",", "matcher", ",", "future", ")", ":", "if", "(", "tag", ",", "matcher", ")", "not", "in", "self", ".", "tag_map", ":", "return", "if", "not", "future", ".", "done", "(", ")", ":", "future", ".",...
Timeout a specific future
[ "Timeout", "a", "specific", "future" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L362-L372
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
EventListener._handle_event_socket_recv
def _handle_event_socket_recv(self, raw): ''' Callback for events on the event sub socket ''' mtag, data = self.event.unpack(raw, self.event.serial) # see if we have any futures that need this info: for (tag, matcher), futures in six.iteritems(self.tag_map): try: is_matched = matcher(mtag, tag) except Exception: log.error('Failed to run a matcher.', exc_info=True) is_matched = False if not is_matched: continue for future in futures: if future.done(): continue future.set_result({'data': data, 'tag': mtag}) self.tag_map[(tag, matcher)].remove(future) if future in self.timeout_map: tornado.ioloop.IOLoop.current().remove_timeout(self.timeout_map[future]) del self.timeout_map[future]
python
def _handle_event_socket_recv(self, raw): ''' Callback for events on the event sub socket ''' mtag, data = self.event.unpack(raw, self.event.serial) # see if we have any futures that need this info: for (tag, matcher), futures in six.iteritems(self.tag_map): try: is_matched = matcher(mtag, tag) except Exception: log.error('Failed to run a matcher.', exc_info=True) is_matched = False if not is_matched: continue for future in futures: if future.done(): continue future.set_result({'data': data, 'tag': mtag}) self.tag_map[(tag, matcher)].remove(future) if future in self.timeout_map: tornado.ioloop.IOLoop.current().remove_timeout(self.timeout_map[future]) del self.timeout_map[future]
[ "def", "_handle_event_socket_recv", "(", "self", ",", "raw", ")", ":", "mtag", ",", "data", "=", "self", ".", "event", ".", "unpack", "(", "raw", ",", "self", ".", "event", ".", "serial", ")", "# see if we have any futures that need this info:", "for", "(", ...
Callback for events on the event sub socket
[ "Callback", "for", "events", "on", "the", "event", "sub", "socket" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L374-L398
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler._verify_client
def _verify_client(self, low): ''' Verify that the client is in fact one we have ''' if 'client' not in low or low.get('client') not in self.saltclients: self.set_status(400) self.write("400 Invalid Client: Client not found in salt clients") self.finish() return False return True
python
def _verify_client(self, low): ''' Verify that the client is in fact one we have ''' if 'client' not in low or low.get('client') not in self.saltclients: self.set_status(400) self.write("400 Invalid Client: Client not found in salt clients") self.finish() return False return True
[ "def", "_verify_client", "(", "self", ",", "low", ")", ":", "if", "'client'", "not", "in", "low", "or", "low", ".", "get", "(", "'client'", ")", "not", "in", "self", ".", "saltclients", ":", "self", ".", "set_status", "(", "400", ")", "self", ".", ...
Verify that the client is in fact one we have
[ "Verify", "that", "the", "client", "is", "in", "fact", "one", "we", "have" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L407-L416
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler.initialize
def initialize(self): ''' Initialize the handler before requests are called ''' if not hasattr(self.application, 'event_listener'): log.debug('init a listener') self.application.event_listener = EventListener( self.application.mod_opts, self.application.opts, ) if not hasattr(self, 'saltclients'): local_client = salt.client.get_local_client(mopts=self.application.opts) self.saltclients = { 'local': local_client.run_job_async, # not the actual client we'll use.. but its what we'll use to get args 'local_async': local_client.run_job_async, 'runner': salt.runner.RunnerClient(opts=self.application.opts).cmd_async, 'runner_async': None, # empty, since we use the same client as `runner` } if not hasattr(self, 'ckminions'): self.ckminions = salt.utils.minions.CkMinions(self.application.opts)
python
def initialize(self): ''' Initialize the handler before requests are called ''' if not hasattr(self.application, 'event_listener'): log.debug('init a listener') self.application.event_listener = EventListener( self.application.mod_opts, self.application.opts, ) if not hasattr(self, 'saltclients'): local_client = salt.client.get_local_client(mopts=self.application.opts) self.saltclients = { 'local': local_client.run_job_async, # not the actual client we'll use.. but its what we'll use to get args 'local_async': local_client.run_job_async, 'runner': salt.runner.RunnerClient(opts=self.application.opts).cmd_async, 'runner_async': None, # empty, since we use the same client as `runner` } if not hasattr(self, 'ckminions'): self.ckminions = salt.utils.minions.CkMinions(self.application.opts)
[ "def", "initialize", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ".", "application", ",", "'event_listener'", ")", ":", "log", ".", "debug", "(", "'init a listener'", ")", "self", ".", "application", ".", "event_listener", "=", "EventListener...
Initialize the handler before requests are called
[ "Initialize", "the", "handler", "before", "requests", "are", "called" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L418-L440
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler.token
def token(self): ''' The token used for the request ''' # find the token (cookie or headers) if AUTH_TOKEN_HEADER in self.request.headers: return self.request.headers[AUTH_TOKEN_HEADER] else: return self.get_cookie(AUTH_COOKIE_NAME)
python
def token(self): ''' The token used for the request ''' # find the token (cookie or headers) if AUTH_TOKEN_HEADER in self.request.headers: return self.request.headers[AUTH_TOKEN_HEADER] else: return self.get_cookie(AUTH_COOKIE_NAME)
[ "def", "token", "(", "self", ")", ":", "# find the token (cookie or headers)", "if", "AUTH_TOKEN_HEADER", "in", "self", ".", "request", ".", "headers", ":", "return", "self", ".", "request", ".", "headers", "[", "AUTH_TOKEN_HEADER", "]", "else", ":", "return", ...
The token used for the request
[ "The", "token", "used", "for", "the", "request" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L443-L451
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler._verify_auth
def _verify_auth(self): ''' Boolean whether the request is auth'd ''' return self.token and bool(self.application.auth.get_tok(self.token))
python
def _verify_auth(self): ''' Boolean whether the request is auth'd ''' return self.token and bool(self.application.auth.get_tok(self.token))
[ "def", "_verify_auth", "(", "self", ")", ":", "return", "self", ".", "token", "and", "bool", "(", "self", ".", "application", ".", "auth", ".", "get_tok", "(", "self", ".", "token", ")", ")" ]
Boolean whether the request is auth'd
[ "Boolean", "whether", "the", "request", "is", "auth", "d" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L453-L458
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler.prepare
def prepare(self): ''' Run before get/posts etc. Pre-flight checks: - verify that we can speak back to them (compatible accept header) ''' # Find an acceptable content-type accept_header = self.request.headers.get('Accept', '*/*') # Ignore any parameter, including q (quality) one parsed_accept_header = [cgi.parse_header(h)[0] for h in accept_header.split(',')] def find_acceptable_content_type(parsed_accept_header): for media_range in parsed_accept_header: for content_type, dumper in self.ct_out_map: if fnmatch.fnmatch(content_type, media_range): return content_type, dumper return None, None content_type, dumper = find_acceptable_content_type(parsed_accept_header) # better return message? if not content_type: self.send_error(406) self.content_type = content_type self.dumper = dumper # do the common parts self.start = time.time() self.connected = True self.lowstate = self._get_lowstate()
python
def prepare(self): ''' Run before get/posts etc. Pre-flight checks: - verify that we can speak back to them (compatible accept header) ''' # Find an acceptable content-type accept_header = self.request.headers.get('Accept', '*/*') # Ignore any parameter, including q (quality) one parsed_accept_header = [cgi.parse_header(h)[0] for h in accept_header.split(',')] def find_acceptable_content_type(parsed_accept_header): for media_range in parsed_accept_header: for content_type, dumper in self.ct_out_map: if fnmatch.fnmatch(content_type, media_range): return content_type, dumper return None, None content_type, dumper = find_acceptable_content_type(parsed_accept_header) # better return message? if not content_type: self.send_error(406) self.content_type = content_type self.dumper = dumper # do the common parts self.start = time.time() self.connected = True self.lowstate = self._get_lowstate()
[ "def", "prepare", "(", "self", ")", ":", "# Find an acceptable content-type", "accept_header", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "'Accept'", ",", "'*/*'", ")", "# Ignore any parameter, including q (quality) one", "parsed_accept_header", "=", ...
Run before get/posts etc. Pre-flight checks: - verify that we can speak back to them (compatible accept header)
[ "Run", "before", "get", "/", "posts", "etc", ".", "Pre", "-", "flight", "checks", ":", "-", "verify", "that", "we", "can", "speak", "back", "to", "them", "(", "compatible", "accept", "header", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L460-L490
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler.serialize
def serialize(self, data): ''' Serlialize the output based on the Accept header ''' self.set_header('Content-Type', self.content_type) return self.dumper(data)
python
def serialize(self, data): ''' Serlialize the output based on the Accept header ''' self.set_header('Content-Type', self.content_type) return self.dumper(data)
[ "def", "serialize", "(", "self", ",", "data", ")", ":", "self", ".", "set_header", "(", "'Content-Type'", ",", "self", ".", "content_type", ")", "return", "self", ".", "dumper", "(", "data", ")" ]
Serlialize the output based on the Accept header
[ "Serlialize", "the", "output", "based", "on", "the", "Accept", "header" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L514-L520
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler._form_loader
def _form_loader(self, _): ''' function to get the data from the urlencoded forms ignore the data passed in and just get the args from wherever they are ''' data = {} for key in self.request.arguments: val = self.get_arguments(key) if len(val) == 1: data[key] = val[0] else: data[key] = val return data
python
def _form_loader(self, _): ''' function to get the data from the urlencoded forms ignore the data passed in and just get the args from wherever they are ''' data = {} for key in self.request.arguments: val = self.get_arguments(key) if len(val) == 1: data[key] = val[0] else: data[key] = val return data
[ "def", "_form_loader", "(", "self", ",", "_", ")", ":", "data", "=", "{", "}", "for", "key", "in", "self", ".", "request", ".", "arguments", ":", "val", "=", "self", ".", "get_arguments", "(", "key", ")", "if", "len", "(", "val", ")", "==", "1", ...
function to get the data from the urlencoded forms ignore the data passed in and just get the args from wherever they are
[ "function", "to", "get", "the", "data", "from", "the", "urlencoded", "forms", "ignore", "the", "data", "passed", "in", "and", "just", "get", "the", "args", "from", "wherever", "they", "are" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L522-L534
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler.deserialize
def deserialize(self, data): ''' Deserialize the data based on request content type headers ''' ct_in_map = { 'application/x-www-form-urlencoded': self._form_loader, 'application/json': salt.utils.json.loads, 'application/x-yaml': salt.utils.yaml.safe_load, 'text/yaml': salt.utils.yaml.safe_load, # because people are terrible and don't mean what they say 'text/plain': salt.utils.json.loads } try: # Use cgi.parse_header to correctly separate parameters from value value, parameters = cgi.parse_header(self.request.headers['Content-Type']) return ct_in_map[value](tornado.escape.native_str(data)) except KeyError: self.send_error(406) except ValueError: self.send_error(400)
python
def deserialize(self, data): ''' Deserialize the data based on request content type headers ''' ct_in_map = { 'application/x-www-form-urlencoded': self._form_loader, 'application/json': salt.utils.json.loads, 'application/x-yaml': salt.utils.yaml.safe_load, 'text/yaml': salt.utils.yaml.safe_load, # because people are terrible and don't mean what they say 'text/plain': salt.utils.json.loads } try: # Use cgi.parse_header to correctly separate parameters from value value, parameters = cgi.parse_header(self.request.headers['Content-Type']) return ct_in_map[value](tornado.escape.native_str(data)) except KeyError: self.send_error(406) except ValueError: self.send_error(400)
[ "def", "deserialize", "(", "self", ",", "data", ")", ":", "ct_in_map", "=", "{", "'application/x-www-form-urlencoded'", ":", "self", ".", "_form_loader", ",", "'application/json'", ":", "salt", ".", "utils", ".", "json", ".", "loads", ",", "'application/x-yaml'"...
Deserialize the data based on request content type headers
[ "Deserialize", "the", "data", "based", "on", "request", "content", "type", "headers" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L536-L556
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler._get_lowstate
def _get_lowstate(self): ''' Format the incoming data into a lowstate object ''' if not self.request.body: return data = self.deserialize(self.request.body) self.request_payload = copy(data) if data and 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] if not isinstance(data, list): lowstate = [data] else: lowstate = data return lowstate
python
def _get_lowstate(self): ''' Format the incoming data into a lowstate object ''' if not self.request.body: return data = self.deserialize(self.request.body) self.request_payload = copy(data) if data and 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] if not isinstance(data, list): lowstate = [data] else: lowstate = data return lowstate
[ "def", "_get_lowstate", "(", "self", ")", ":", "if", "not", "self", ".", "request", ".", "body", ":", "return", "data", "=", "self", ".", "deserialize", "(", "self", ".", "request", ".", "body", ")", "self", ".", "request_payload", "=", "copy", "(", ...
Format the incoming data into a lowstate object
[ "Format", "the", "incoming", "data", "into", "a", "lowstate", "object" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L558-L575
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler.set_default_headers
def set_default_headers(self): ''' Set default CORS headers ''' mod_opts = self.application.mod_opts if mod_opts.get('cors_origin'): origin = self.request.headers.get('Origin') allowed_origin = _check_cors_origin(origin, mod_opts['cors_origin']) if allowed_origin: self.set_header("Access-Control-Allow-Origin", allowed_origin)
python
def set_default_headers(self): ''' Set default CORS headers ''' mod_opts = self.application.mod_opts if mod_opts.get('cors_origin'): origin = self.request.headers.get('Origin') allowed_origin = _check_cors_origin(origin, mod_opts['cors_origin']) if allowed_origin: self.set_header("Access-Control-Allow-Origin", allowed_origin)
[ "def", "set_default_headers", "(", "self", ")", ":", "mod_opts", "=", "self", ".", "application", ".", "mod_opts", "if", "mod_opts", ".", "get", "(", "'cors_origin'", ")", ":", "origin", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "'Ori...
Set default CORS headers
[ "Set", "default", "CORS", "headers" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L577-L589
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
BaseSaltAPIHandler.options
def options(self, *args, **kwargs): ''' Return CORS headers for preflight requests ''' # Allow X-Auth-Token in requests request_headers = self.request.headers.get('Access-Control-Request-Headers') allowed_headers = request_headers.split(',') # Filter allowed header here if needed. # Allow request headers self.set_header('Access-Control-Allow-Headers', ','.join(allowed_headers)) # Allow X-Auth-Token in responses self.set_header('Access-Control-Expose-Headers', 'X-Auth-Token') # Allow all methods self.set_header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST') self.set_status(204) self.finish()
python
def options(self, *args, **kwargs): ''' Return CORS headers for preflight requests ''' # Allow X-Auth-Token in requests request_headers = self.request.headers.get('Access-Control-Request-Headers') allowed_headers = request_headers.split(',') # Filter allowed header here if needed. # Allow request headers self.set_header('Access-Control-Allow-Headers', ','.join(allowed_headers)) # Allow X-Auth-Token in responses self.set_header('Access-Control-Expose-Headers', 'X-Auth-Token') # Allow all methods self.set_header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST') self.set_status(204) self.finish()
[ "def", "options", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Allow X-Auth-Token in requests", "request_headers", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "'Access-Control-Request-Headers'", ")", "allowed_headers", "...
Return CORS headers for preflight requests
[ "Return", "CORS", "headers", "for", "preflight", "requests" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L591-L611
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
SaltAuthHandler.get
def get(self): ''' All logins are done over post, this is a parked endpoint .. http:get:: /login :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 401 Unauthorized Content-Type: application/json Content-Length: 58 {"status": "401 Unauthorized", "return": "Please log in"} ''' self.set_status(401) self.set_header('WWW-Authenticate', 'Session') ret = {'status': '401 Unauthorized', 'return': 'Please log in'} self.write(self.serialize(ret))
python
def get(self): ''' All logins are done over post, this is a parked endpoint .. http:get:: /login :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 401 Unauthorized Content-Type: application/json Content-Length: 58 {"status": "401 Unauthorized", "return": "Please log in"} ''' self.set_status(401) self.set_header('WWW-Authenticate', 'Session') ret = {'status': '401 Unauthorized', 'return': 'Please log in'} self.write(self.serialize(ret))
[ "def", "get", "(", "self", ")", ":", "self", ".", "set_status", "(", "401", ")", "self", ".", "set_header", "(", "'WWW-Authenticate'", ",", "'Session'", ")", "ret", "=", "{", "'status'", ":", "'401 Unauthorized'", ",", "'return'", ":", "'Please log in'", "...
All logins are done over post, this is a parked endpoint .. http:get:: /login :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 401 Unauthorized Content-Type: application/json Content-Length: 58 {"status": "401 Unauthorized", "return": "Please log in"}
[ "All", "logins", "are", "done", "over", "post", "this", "is", "a", "parked", "endpoint" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L618-L655
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
SaltAuthHandler.post
def post(self): ''' :ref:`Authenticate <rest_tornado-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :status 500: |500| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -H "Accept: application/json" \\ -d username='saltuser' \\ -d password='saltpass' \\ -d eauth='pam' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/x-www-form-urlencoded Accept: application/json username=saltuser&password=saltpass&eauth=pam **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' try: if not isinstance(self.request_payload, dict): self.send_error(400) return creds = {'username': self.request_payload['username'], 'password': self.request_payload['password'], 'eauth': self.request_payload['eauth'], } # if any of the args are missing, its a bad request except KeyError: self.send_error(400) return token = self.application.auth.mk_token(creds) if 'token' not in token: # TODO: nicer error message # 'Could not authenticate using provided credentials') self.send_error(401) # return since we don't want to execute any more return # Grab eauth config for the current backend for the current user try: eauth = self.application.opts['external_auth'][token['eauth']] # Get sum of '*' perms, user-specific perms, and group-specific perms _perms = eauth.get(token['name'], []) _perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: _perms.extend(eauth['{0}%'.format(group)]) # dedup. perm can be a complex dict, so we cant use set perms = [] for perm in _perms: if perm not in perms: perms.append(perm) # If we can't find the creds, then they aren't authorized except KeyError: self.send_error(401) return except (AttributeError, IndexError): log.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) # TODO better error -- 'Configuration for external_auth could not be read.' self.send_error(500) return ret = {'return': [{ 'token': token['token'], 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms, }]} self.write(self.serialize(ret))
python
def post(self): ''' :ref:`Authenticate <rest_tornado-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :status 500: |500| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -H "Accept: application/json" \\ -d username='saltuser' \\ -d password='saltpass' \\ -d eauth='pam' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/x-www-form-urlencoded Accept: application/json username=saltuser&password=saltpass&eauth=pam **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' try: if not isinstance(self.request_payload, dict): self.send_error(400) return creds = {'username': self.request_payload['username'], 'password': self.request_payload['password'], 'eauth': self.request_payload['eauth'], } # if any of the args are missing, its a bad request except KeyError: self.send_error(400) return token = self.application.auth.mk_token(creds) if 'token' not in token: # TODO: nicer error message # 'Could not authenticate using provided credentials') self.send_error(401) # return since we don't want to execute any more return # Grab eauth config for the current backend for the current user try: eauth = self.application.opts['external_auth'][token['eauth']] # Get sum of '*' perms, user-specific perms, and group-specific perms _perms = eauth.get(token['name'], []) _perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: _perms.extend(eauth['{0}%'.format(group)]) # dedup. perm can be a complex dict, so we cant use set perms = [] for perm in _perms: if perm not in perms: perms.append(perm) # If we can't find the creds, then they aren't authorized except KeyError: self.send_error(401) return except (AttributeError, IndexError): log.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) # TODO better error -- 'Configuration for external_auth could not be read.' self.send_error(500) return ret = {'return': [{ 'token': token['token'], 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms, }]} self.write(self.serialize(ret))
[ "def", "post", "(", "self", ")", ":", "try", ":", "if", "not", "isinstance", "(", "self", ".", "request_payload", ",", "dict", ")", ":", "self", ".", "send_error", "(", "400", ")", "return", "creds", "=", "{", "'username'", ":", "self", ".", "request...
:ref:`Authenticate <rest_tornado-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :status 500: |500| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -H "Accept: application/json" \\ -d username='saltuser' \\ -d password='saltpass' \\ -d eauth='pam' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/x-www-form-urlencoded Accept: application/json username=saltuser&password=saltpass&eauth=pam **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }}
[ ":", "ref", ":", "Authenticate", "<rest_tornado", "-", "auth", ">", "against", "Salt", "s", "eauth", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L658-L788
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
SaltAPIHandler.get
def get(self): ''' An endpoint to determine salt-api capabilities .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Legnth: 83 {"clients": ["local", "local_async", "runner", "runner_async"], "return": "Welcome"} ''' ret = {"clients": list(self.saltclients.keys()), "return": "Welcome"} self.write(self.serialize(ret))
python
def get(self): ''' An endpoint to determine salt-api capabilities .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Legnth: 83 {"clients": ["local", "local_async", "runner", "runner_async"], "return": "Welcome"} ''' ret = {"clients": list(self.saltclients.keys()), "return": "Welcome"} self.write(self.serialize(ret))
[ "def", "get", "(", "self", ")", ":", "ret", "=", "{", "\"clients\"", ":", "list", "(", "self", ".", "saltclients", ".", "keys", "(", ")", ")", ",", "\"return\"", ":", "\"Welcome\"", "}", "self", ".", "write", "(", "self", ".", "serialize", "(", "re...
An endpoint to determine salt-api capabilities .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Legnth: 83 {"clients": ["local", "local_async", "runner", "runner_async"], "return": "Welcome"}
[ "An", "endpoint", "to", "determine", "salt", "-", "api", "capabilities" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L795-L831
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
SaltAPIHandler.disbatch
def disbatch(self): ''' Disbatch all lowstates to the appropriate clients ''' ret = [] # check clients before going, we want to throw 400 if one is bad for low in self.lowstate: if not self._verify_client(low): return # Make sure we have 'token' or 'username'/'password' in each low chunk. # Salt will verify the credentials are correct. if self.token is not None and 'token' not in low: low['token'] = self.token if not (('token' in low) or ('username' in low and 'password' in low and 'eauth' in low)): ret.append('Failed to authenticate') break # disbatch to the correct handler try: chunk_ret = yield getattr(self, '_disbatch_{0}'.format(low['client']))(low) ret.append(chunk_ret) except (AuthenticationError, AuthorizationError, EauthAuthenticationError): ret.append('Failed to authenticate') break except Exception as ex: ret.append('Unexpected exception while handling request: {0}'.format(ex)) log.error('Unexpected exception while handling request:', exc_info=True) if not self._finished: self.write(self.serialize({'return': ret})) self.finish()
python
def disbatch(self): ''' Disbatch all lowstates to the appropriate clients ''' ret = [] # check clients before going, we want to throw 400 if one is bad for low in self.lowstate: if not self._verify_client(low): return # Make sure we have 'token' or 'username'/'password' in each low chunk. # Salt will verify the credentials are correct. if self.token is not None and 'token' not in low: low['token'] = self.token if not (('token' in low) or ('username' in low and 'password' in low and 'eauth' in low)): ret.append('Failed to authenticate') break # disbatch to the correct handler try: chunk_ret = yield getattr(self, '_disbatch_{0}'.format(low['client']))(low) ret.append(chunk_ret) except (AuthenticationError, AuthorizationError, EauthAuthenticationError): ret.append('Failed to authenticate') break except Exception as ex: ret.append('Unexpected exception while handling request: {0}'.format(ex)) log.error('Unexpected exception while handling request:', exc_info=True) if not self._finished: self.write(self.serialize({'return': ret})) self.finish()
[ "def", "disbatch", "(", "self", ")", ":", "ret", "=", "[", "]", "# check clients before going, we want to throw 400 if one is bad", "for", "low", "in", "self", ".", "lowstate", ":", "if", "not", "self", ".", "_verify_client", "(", "low", ")", ":", "return", "#...
Disbatch all lowstates to the appropriate clients
[ "Disbatch", "all", "lowstates", "to", "the", "appropriate", "clients" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L912-L946
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
SaltAPIHandler._disbatch_local
def _disbatch_local(self, chunk): ''' Dispatch local client commands ''' # Generate jid and find all minions before triggering a job to subscribe all returns from minions full_return = chunk.pop('full_return', False) chunk['jid'] = salt.utils.jid.gen_jid(self.application.opts) if not chunk.get('jid', None) else chunk['jid'] minions = set(self.ckminions.check_minions(chunk['tgt'], chunk.get('tgt_type', 'glob'))) def subscribe_minion(minion): salt_evt = self.application.event_listener.get_event( self, tag='salt/job/{}/ret/{}'.format(chunk['jid'], minion), matcher=EventListener.exact_matcher) syndic_evt = self.application.event_listener.get_event( self, tag='syndic/job/{}/ret/{}'.format(chunk['jid'], minion), matcher=EventListener.exact_matcher) return salt_evt, syndic_evt # start listening for the event before we fire the job to avoid races events = [] for minion in minions: salt_evt, syndic_evt = subscribe_minion(minion) events.append(salt_evt) events.append(syndic_evt) f_call = self._format_call_run_job_async(chunk) # fire a job off pub_data = yield self.saltclients['local'](*f_call.get('args', ()), **f_call.get('kwargs', {})) # if the job didn't publish, lets not wait around for nothing # TODO: set header?? if 'jid' not in pub_data: for future in events: try: future.set_result(None) except Exception: pass raise tornado.gen.Return('No minions matched the target. No command was sent, no jid was assigned.') # get_event for missing minion for minion in list(set(pub_data['minions']) - set(minions)): salt_evt, syndic_evt = subscribe_minion(minion) events.append(salt_evt) events.append(syndic_evt) # Map of minion_id -> returned for all minions we think we need to wait on minions = {m: False for m in pub_data['minions']} # minimum time required for return to complete. By default no waiting, if # we are a syndic then we must wait syndic_wait at a minimum min_wait_time = Future() min_wait_time.set_result(True) # wait syndic a while to avoid missing published events if self.application.opts['order_masters']: min_wait_time = tornado.gen.sleep(self.application.opts['syndic_wait']) # To ensure job_not_running and all_return are terminated by each other, communicate using a future is_timed_out = tornado.gen.sleep(self.application.opts['gather_job_timeout']) is_finished = Future() # ping until the job is not running, while doing so, if we see new minions returning # that they are running the job, add them to the list tornado.ioloop.IOLoop.current().spawn_callback(self.job_not_running, pub_data['jid'], chunk['tgt'], f_call['kwargs']['tgt_type'], minions, is_finished) def more_todo(): ''' Check if there are any more minions we are waiting on returns from ''' return any(x is False for x in six.itervalues(minions)) # here we want to follow the behavior of LocalClient.get_iter_returns # namely we want to wait at least syndic_wait (assuming we are a syndic) # and that there are no more jobs running on minions. We are allowed to exit # early if gather_job_timeout has been exceeded chunk_ret = {} while True: to_wait = events+[is_finished, is_timed_out] if not min_wait_time.done(): to_wait += [min_wait_time] def cancel_inflight_futures(): for event in to_wait: if not event.done() and event is not is_timed_out: event.set_result(None) f = yield Any(to_wait) try: # When finished entire routine, cleanup other futures and return result if f is is_finished or f is is_timed_out: cancel_inflight_futures() raise tornado.gen.Return(chunk_ret) elif f is min_wait_time: if not more_todo(): cancel_inflight_futures() raise tornado.gen.Return(chunk_ret) continue f_result = f.result() if f in events: events.remove(f) # if this is a start, then we need to add it to the pile if f_result['tag'].endswith('/new'): for minion_id in f_result['data']['minions']: if minion_id not in minions: minions[minion_id] = False else: chunk_ret[f_result['data']['id']] = f_result if full_return else f_result['data']['return'] # clear finished event future minions[f_result['data']['id']] = True # if there are no more minions to wait for, then we are done if not more_todo() and min_wait_time.done(): cancel_inflight_futures() raise tornado.gen.Return(chunk_ret) except TimeoutException: break
python
def _disbatch_local(self, chunk): ''' Dispatch local client commands ''' # Generate jid and find all minions before triggering a job to subscribe all returns from minions full_return = chunk.pop('full_return', False) chunk['jid'] = salt.utils.jid.gen_jid(self.application.opts) if not chunk.get('jid', None) else chunk['jid'] minions = set(self.ckminions.check_minions(chunk['tgt'], chunk.get('tgt_type', 'glob'))) def subscribe_minion(minion): salt_evt = self.application.event_listener.get_event( self, tag='salt/job/{}/ret/{}'.format(chunk['jid'], minion), matcher=EventListener.exact_matcher) syndic_evt = self.application.event_listener.get_event( self, tag='syndic/job/{}/ret/{}'.format(chunk['jid'], minion), matcher=EventListener.exact_matcher) return salt_evt, syndic_evt # start listening for the event before we fire the job to avoid races events = [] for minion in minions: salt_evt, syndic_evt = subscribe_minion(minion) events.append(salt_evt) events.append(syndic_evt) f_call = self._format_call_run_job_async(chunk) # fire a job off pub_data = yield self.saltclients['local'](*f_call.get('args', ()), **f_call.get('kwargs', {})) # if the job didn't publish, lets not wait around for nothing # TODO: set header?? if 'jid' not in pub_data: for future in events: try: future.set_result(None) except Exception: pass raise tornado.gen.Return('No minions matched the target. No command was sent, no jid was assigned.') # get_event for missing minion for minion in list(set(pub_data['minions']) - set(minions)): salt_evt, syndic_evt = subscribe_minion(minion) events.append(salt_evt) events.append(syndic_evt) # Map of minion_id -> returned for all minions we think we need to wait on minions = {m: False for m in pub_data['minions']} # minimum time required for return to complete. By default no waiting, if # we are a syndic then we must wait syndic_wait at a minimum min_wait_time = Future() min_wait_time.set_result(True) # wait syndic a while to avoid missing published events if self.application.opts['order_masters']: min_wait_time = tornado.gen.sleep(self.application.opts['syndic_wait']) # To ensure job_not_running and all_return are terminated by each other, communicate using a future is_timed_out = tornado.gen.sleep(self.application.opts['gather_job_timeout']) is_finished = Future() # ping until the job is not running, while doing so, if we see new minions returning # that they are running the job, add them to the list tornado.ioloop.IOLoop.current().spawn_callback(self.job_not_running, pub_data['jid'], chunk['tgt'], f_call['kwargs']['tgt_type'], minions, is_finished) def more_todo(): ''' Check if there are any more minions we are waiting on returns from ''' return any(x is False for x in six.itervalues(minions)) # here we want to follow the behavior of LocalClient.get_iter_returns # namely we want to wait at least syndic_wait (assuming we are a syndic) # and that there are no more jobs running on minions. We are allowed to exit # early if gather_job_timeout has been exceeded chunk_ret = {} while True: to_wait = events+[is_finished, is_timed_out] if not min_wait_time.done(): to_wait += [min_wait_time] def cancel_inflight_futures(): for event in to_wait: if not event.done() and event is not is_timed_out: event.set_result(None) f = yield Any(to_wait) try: # When finished entire routine, cleanup other futures and return result if f is is_finished or f is is_timed_out: cancel_inflight_futures() raise tornado.gen.Return(chunk_ret) elif f is min_wait_time: if not more_todo(): cancel_inflight_futures() raise tornado.gen.Return(chunk_ret) continue f_result = f.result() if f in events: events.remove(f) # if this is a start, then we need to add it to the pile if f_result['tag'].endswith('/new'): for minion_id in f_result['data']['minions']: if minion_id not in minions: minions[minion_id] = False else: chunk_ret[f_result['data']['id']] = f_result if full_return else f_result['data']['return'] # clear finished event future minions[f_result['data']['id']] = True # if there are no more minions to wait for, then we are done if not more_todo() and min_wait_time.done(): cancel_inflight_futures() raise tornado.gen.Return(chunk_ret) except TimeoutException: break
[ "def", "_disbatch_local", "(", "self", ",", "chunk", ")", ":", "# Generate jid and find all minions before triggering a job to subscribe all returns from minions", "full_return", "=", "chunk", ".", "pop", "(", "'full_return'", ",", "False", ")", "chunk", "[", "'jid'", "]"...
Dispatch local client commands
[ "Dispatch", "local", "client", "commands" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L949-L1070
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
SaltAPIHandler.job_not_running
def job_not_running(self, jid, tgt, tgt_type, minions, is_finished): ''' Return a future which will complete once jid (passed in) is no longer running on tgt ''' ping_pub_data = yield self.saltclients['local'](tgt, 'saltutil.find_job', [jid], tgt_type=tgt_type) ping_tag = tagify([ping_pub_data['jid'], 'ret'], 'job') minion_running = False while True: try: event = self.application.event_listener.get_event(self, tag=ping_tag, timeout=self.application.opts['gather_job_timeout']) event = yield event except TimeoutException: if not event.done(): event.set_result(None) if not minion_running or is_finished.done(): raise tornado.gen.Return(True) else: ping_pub_data = yield self.saltclients['local'](tgt, 'saltutil.find_job', [jid], tgt_type=tgt_type) ping_tag = tagify([ping_pub_data['jid'], 'ret'], 'job') minion_running = False continue # Minions can return, we want to see if the job is running... if event['data'].get('return', {}) == {}: continue if event['data']['id'] not in minions: minions[event['data']['id']] = False minion_running = True
python
def job_not_running(self, jid, tgt, tgt_type, minions, is_finished): ''' Return a future which will complete once jid (passed in) is no longer running on tgt ''' ping_pub_data = yield self.saltclients['local'](tgt, 'saltutil.find_job', [jid], tgt_type=tgt_type) ping_tag = tagify([ping_pub_data['jid'], 'ret'], 'job') minion_running = False while True: try: event = self.application.event_listener.get_event(self, tag=ping_tag, timeout=self.application.opts['gather_job_timeout']) event = yield event except TimeoutException: if not event.done(): event.set_result(None) if not minion_running or is_finished.done(): raise tornado.gen.Return(True) else: ping_pub_data = yield self.saltclients['local'](tgt, 'saltutil.find_job', [jid], tgt_type=tgt_type) ping_tag = tagify([ping_pub_data['jid'], 'ret'], 'job') minion_running = False continue # Minions can return, we want to see if the job is running... if event['data'].get('return', {}) == {}: continue if event['data']['id'] not in minions: minions[event['data']['id']] = False minion_running = True
[ "def", "job_not_running", "(", "self", ",", "jid", ",", "tgt", ",", "tgt_type", ",", "minions", ",", "is_finished", ")", ":", "ping_pub_data", "=", "yield", "self", ".", "saltclients", "[", "'local'", "]", "(", "tgt", ",", "'saltutil.find_job'", ",", "[", ...
Return a future which will complete once jid (passed in) is no longer running on tgt
[ "Return", "a", "future", "which", "will", "complete", "once", "jid", "(", "passed", "in", ")", "is", "no", "longer", "running", "on", "tgt" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1073-L1111
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
SaltAPIHandler._disbatch_local_async
def _disbatch_local_async(self, chunk): ''' Disbatch local client_async commands ''' f_call = self._format_call_run_job_async(chunk) # fire a job off pub_data = yield self.saltclients['local_async'](*f_call.get('args', ()), **f_call.get('kwargs', {})) raise tornado.gen.Return(pub_data)
python
def _disbatch_local_async(self, chunk): ''' Disbatch local client_async commands ''' f_call = self._format_call_run_job_async(chunk) # fire a job off pub_data = yield self.saltclients['local_async'](*f_call.get('args', ()), **f_call.get('kwargs', {})) raise tornado.gen.Return(pub_data)
[ "def", "_disbatch_local_async", "(", "self", ",", "chunk", ")", ":", "f_call", "=", "self", ".", "_format_call_run_job_async", "(", "chunk", ")", "# fire a job off", "pub_data", "=", "yield", "self", ".", "saltclients", "[", "'local_async'", "]", "(", "*", "f_...
Disbatch local client_async commands
[ "Disbatch", "local", "client_async", "commands" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1114-L1122
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
SaltAPIHandler._disbatch_runner
def _disbatch_runner(self, chunk): ''' Disbatch runner client commands ''' full_return = chunk.pop('full_return', False) pub_data = self.saltclients['runner'](chunk) tag = pub_data['tag'] + '/ret' try: event = yield self.application.event_listener.get_event(self, tag=tag) # only return the return data ret = event if full_return else event['data']['return'] raise tornado.gen.Return(ret) except TimeoutException: raise tornado.gen.Return('Timeout waiting for runner to execute')
python
def _disbatch_runner(self, chunk): ''' Disbatch runner client commands ''' full_return = chunk.pop('full_return', False) pub_data = self.saltclients['runner'](chunk) tag = pub_data['tag'] + '/ret' try: event = yield self.application.event_listener.get_event(self, tag=tag) # only return the return data ret = event if full_return else event['data']['return'] raise tornado.gen.Return(ret) except TimeoutException: raise tornado.gen.Return('Timeout waiting for runner to execute')
[ "def", "_disbatch_runner", "(", "self", ",", "chunk", ")", ":", "full_return", "=", "chunk", ".", "pop", "(", "'full_return'", ",", "False", ")", "pub_data", "=", "self", ".", "saltclients", "[", "'runner'", "]", "(", "chunk", ")", "tag", "=", "pub_data"...
Disbatch runner client commands
[ "Disbatch", "runner", "client", "commands" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1125-L1139
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
SaltAPIHandler._disbatch_runner_async
def _disbatch_runner_async(self, chunk): ''' Disbatch runner client_async commands ''' pub_data = self.saltclients['runner'](chunk) raise tornado.gen.Return(pub_data)
python
def _disbatch_runner_async(self, chunk): ''' Disbatch runner client_async commands ''' pub_data = self.saltclients['runner'](chunk) raise tornado.gen.Return(pub_data)
[ "def", "_disbatch_runner_async", "(", "self", ",", "chunk", ")", ":", "pub_data", "=", "self", ".", "saltclients", "[", "'runner'", "]", "(", "chunk", ")", "raise", "tornado", ".", "gen", ".", "Return", "(", "pub_data", ")" ]
Disbatch runner client_async commands
[ "Disbatch", "runner", "client_async", "commands" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1142-L1147
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
MinionSaltAPIHandler.get
def get(self, mid=None): # pylint: disable=W0221 ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' # if you aren't authenticated, redirect to login if not self._verify_auth(): self.redirect('/login') return self.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] self.disbatch()
python
def get(self, mid=None): # pylint: disable=W0221 ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' # if you aren't authenticated, redirect to login if not self._verify_auth(): self.redirect('/login') return self.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] self.disbatch()
[ "def", "get", "(", "self", ",", "mid", "=", "None", ")", ":", "# pylint: disable=W0221", "# if you aren't authenticated, redirect to login", "if", "not", "self", ".", "_verify_auth", "(", ")", ":", "self", ".", "redirect", "(", "'/login'", ")", "return", "self",...
A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ...
[ "A", "convenience", "URL", "for", "getting", "lists", "of", "minions", "or", "getting", "minion", "details" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1165-L1214
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
MinionSaltAPIHandler.post
def post(self): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -H "Accept: application/x-yaml" \\ -d tgt='*' \\ -d fun='status.diskusage' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 26 Content-Type: application/x-www-form-urlencoded tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] ''' # if you aren't authenticated, redirect to login if not self._verify_auth(): self.redirect('/login') return # verify that all lowstates are the correct client type for low in self.lowstate: # if you didn't specify, its fine if 'client' not in low: low['client'] = 'local_async' continue # if you specified something else, we don't do that if low.get('client') != 'local_async': self.set_status(400) self.write('We don\'t serve your kind here') self.finish() return self.disbatch()
python
def post(self): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -H "Accept: application/x-yaml" \\ -d tgt='*' \\ -d fun='status.diskusage' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 26 Content-Type: application/x-www-form-urlencoded tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] ''' # if you aren't authenticated, redirect to login if not self._verify_auth(): self.redirect('/login') return # verify that all lowstates are the correct client type for low in self.lowstate: # if you didn't specify, its fine if 'client' not in low: low['client'] = 'local_async' continue # if you specified something else, we don't do that if low.get('client') != 'local_async': self.set_status(400) self.write('We don\'t serve your kind here') self.finish() return self.disbatch()
[ "def", "post", "(", "self", ")", ":", "# if you aren't authenticated, redirect to login", "if", "not", "self", ".", "_verify_auth", "(", ")", ":", "self", ".", "redirect", "(", "'/login'", ")", "return", "# verify that all lowstates are the correct client type", "for", ...
Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -H "Accept: application/x-yaml" \\ -d tgt='*' \\ -d fun='status.diskusage' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 26 Content-Type: application/x-www-form-urlencoded tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0]
[ "Start", "an", "execution", "command", "and", "immediately", "return", "the", "job", "id" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1217-L1286
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
JobsSaltAPIHandler.get
def get(self, jid=None): # pylint: disable=W0221 ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' # if you aren't authenticated, redirect to login if not self._verify_auth(): self.redirect('/login') return if jid: self.lowstate = [{ 'fun': 'jobs.list_job', 'jid': jid, 'client': 'runner', }] else: self.lowstate = [{ 'fun': 'jobs.list_jobs', 'client': 'runner', }] self.disbatch()
python
def get(self, jid=None): # pylint: disable=W0221 ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' # if you aren't authenticated, redirect to login if not self._verify_auth(): self.redirect('/login') return if jid: self.lowstate = [{ 'fun': 'jobs.list_job', 'jid': jid, 'client': 'runner', }] else: self.lowstate = [{ 'fun': 'jobs.list_jobs', 'client': 'runner', }] self.disbatch()
[ "def", "get", "(", "self", ",", "jid", "=", "None", ")", ":", "# pylint: disable=W0221", "# if you aren't authenticated, redirect to login", "if", "not", "self", ".", "_verify_auth", "(", ")", ":", "self", ".", "redirect", "(", "'/login'", ")", "return", "if", ...
A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06
[ "A", "convenience", "URL", "for", "getting", "lists", "of", "previously", "run", "jobs", "or", "getting", "the", "return", "from", "a", "single", "job" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1294-L1392
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
EventsSaltAPIHandler.get
def get(self): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 data: {'tag': '', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} data: {'tag': '20130802115730568475', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript # Note, you must be authenticated! var source = new EventSource('/events'); source.onopen = function() { console.debug('opening') }; source.onerror = function(e) { console.debug('error!', e) }; source.onmessage = function(e) { console.debug(e.data) }; Or using CORS: .. code-block:: javascript var source = new EventSource('/events', {withCredentials: true}); Some browser clients lack CORS support for the ``EventSource()`` API. Such clients may instead pass the :mailheader:`X-Auth-Token` value as an URL parameter: .. code-block:: bash curl -NsS localhost:8000/events/6d1b722e It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' # if you aren't authenticated, redirect to login if not self._verify_auth(): self.redirect('/login') return # set the streaming headers self.set_header('Content-Type', 'text/event-stream') self.set_header('Cache-Control', 'no-cache') self.set_header('Connection', 'keep-alive') self.write('retry: {0}\n'.format(400)) self.flush() while True: try: event = yield self.application.event_listener.get_event(self) self.write('tag: {0}\n'.format(event.get('tag', ''))) self.write(str('data: {0}\n\n').format(_json_dumps(event))) # future lint: disable=blacklisted-function self.flush() except TimeoutException: break
python
def get(self): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 data: {'tag': '', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} data: {'tag': '20130802115730568475', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript # Note, you must be authenticated! var source = new EventSource('/events'); source.onopen = function() { console.debug('opening') }; source.onerror = function(e) { console.debug('error!', e) }; source.onmessage = function(e) { console.debug(e.data) }; Or using CORS: .. code-block:: javascript var source = new EventSource('/events', {withCredentials: true}); Some browser clients lack CORS support for the ``EventSource()`` API. Such clients may instead pass the :mailheader:`X-Auth-Token` value as an URL parameter: .. code-block:: bash curl -NsS localhost:8000/events/6d1b722e It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' # if you aren't authenticated, redirect to login if not self._verify_auth(): self.redirect('/login') return # set the streaming headers self.set_header('Content-Type', 'text/event-stream') self.set_header('Cache-Control', 'no-cache') self.set_header('Connection', 'keep-alive') self.write('retry: {0}\n'.format(400)) self.flush() while True: try: event = yield self.application.event_listener.get_event(self) self.write('tag: {0}\n'.format(event.get('tag', ''))) self.write(str('data: {0}\n\n').format(_json_dumps(event))) # future lint: disable=blacklisted-function self.flush() except TimeoutException: break
[ "def", "get", "(", "self", ")", ":", "# if you aren't authenticated, redirect to login", "if", "not", "self", ".", "_verify_auth", "(", ")", ":", "self", ".", "redirect", "(", "'/login'", ")", "return", "# set the streaming headers", "self", ".", "set_header", "("...
r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 data: {'tag': '', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} data: {'tag': '20130802115730568475', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript # Note, you must be authenticated! var source = new EventSource('/events'); source.onopen = function() { console.debug('opening') }; source.onerror = function(e) { console.debug('error!', e) }; source.onmessage = function(e) { console.debug(e.data) }; Or using CORS: .. code-block:: javascript var source = new EventSource('/events', {withCredentials: true}); Some browser clients lack CORS support for the ``EventSource()`` API. Such clients may instead pass the :mailheader:`X-Auth-Token` value as an URL parameter: .. code-block:: bash curl -NsS localhost:8000/events/6d1b722e It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}}
[ "r", "An", "HTTP", "stream", "of", "the", "Salt", "master", "event", "bus" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1471-L1584
train
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
WebhookSaltAPIHandler.post
def post(self, tag_suffix=None): # pylint: disable=W0221 ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook -d foo='Foo!' -d bar='Bar!' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/x-www-form-urlencoded foo=Foo&bar=Bar! **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``http://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor: .. code-block:: text Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' disable_auth = self.application.mod_opts.get('webhook_disable_auth') if not disable_auth and not self._verify_auth(): self.redirect('/login') return # if you have the tag, prefix tag = 'salt/netapi/hook' if tag_suffix: tag += tag_suffix # TODO: consolidate?? self.event = salt.utils.event.get_event( 'master', self.application.opts['sock_dir'], self.application.opts['transport'], opts=self.application.opts, listen=False) arguments = {} for argname in self.request.query_arguments: value = self.get_arguments(argname) if len(value) == 1: value = value[0] arguments[argname] = value ret = self.event.fire_event({ 'post': self.request_payload, 'get': arguments, # In Tornado >= v4.0.3, the headers come # back as an HTTPHeaders instance, which # is a dictionary. We must cast this as # a dictionary in order for msgpack to # serialize it. 'headers': dict(self.request.headers), }, tag) self.write(self.serialize({'success': ret}))
python
def post(self, tag_suffix=None): # pylint: disable=W0221 ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook -d foo='Foo!' -d bar='Bar!' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/x-www-form-urlencoded foo=Foo&bar=Bar! **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``http://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor: .. code-block:: text Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' disable_auth = self.application.mod_opts.get('webhook_disable_auth') if not disable_auth and not self._verify_auth(): self.redirect('/login') return # if you have the tag, prefix tag = 'salt/netapi/hook' if tag_suffix: tag += tag_suffix # TODO: consolidate?? self.event = salt.utils.event.get_event( 'master', self.application.opts['sock_dir'], self.application.opts['transport'], opts=self.application.opts, listen=False) arguments = {} for argname in self.request.query_arguments: value = self.get_arguments(argname) if len(value) == 1: value = value[0] arguments[argname] = value ret = self.event.fire_event({ 'post': self.request_payload, 'get': arguments, # In Tornado >= v4.0.3, the headers come # back as an HTTPHeaders instance, which # is a dictionary. We must cast this as # a dictionary in order for msgpack to # serialize it. 'headers': dict(self.request.headers), }, tag) self.write(self.serialize({'success': ret}))
[ "def", "post", "(", "self", ",", "tag_suffix", "=", "None", ")", ":", "# pylint: disable=W0221", "disable_auth", "=", "self", ".", "application", ".", "mod_opts", ".", "get", "(", "'webhook_disable_auth'", ")", "if", "not", "disable_auth", "and", "not", "self"...
Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook -d foo='Foo!' -d bar='Bar!' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/x-www-form-urlencoded foo=Foo&bar=Bar! **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``http://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor: .. code-block:: text Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %}
[ "Fire", "an", "event", "in", "Salt", "with", "a", "custom", "event", "tag", "and", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1628-L1747
train
saltstack/salt
salt/beacons/proxy_example.py
beacon
def beacon(config): ''' Called several times each second https://docs.saltstack.com/en/latest/topics/beacons/#the-beacon-function .. code-block:: yaml beacons: proxy_example: - endpoint: beacon ''' # Important!!! # Although this toy example makes an HTTP call # to get beacon information # please be advised that doing CPU or IO intensive # operations in this method will cause the beacon loop # to block. _config = {} list(map(_config.update, config)) beacon_url = '{0}{1}'.format(__opts__['proxy']['url'], _config['endpoint']) ret = salt.utils.http.query(beacon_url, decode_type='json', decode=True) return [ret['dict']]
python
def beacon(config): ''' Called several times each second https://docs.saltstack.com/en/latest/topics/beacons/#the-beacon-function .. code-block:: yaml beacons: proxy_example: - endpoint: beacon ''' # Important!!! # Although this toy example makes an HTTP call # to get beacon information # please be advised that doing CPU or IO intensive # operations in this method will cause the beacon loop # to block. _config = {} list(map(_config.update, config)) beacon_url = '{0}{1}'.format(__opts__['proxy']['url'], _config['endpoint']) ret = salt.utils.http.query(beacon_url, decode_type='json', decode=True) return [ret['dict']]
[ "def", "beacon", "(", "config", ")", ":", "# Important!!!", "# Although this toy example makes an HTTP call", "# to get beacon information", "# please be advised that doing CPU or IO intensive", "# operations in this method will cause the beacon loop", "# to block.", "_config", "=", "{",...
Called several times each second https://docs.saltstack.com/en/latest/topics/beacons/#the-beacon-function .. code-block:: yaml beacons: proxy_example: - endpoint: beacon
[ "Called", "several", "times", "each", "second", "https", ":", "//", "docs", ".", "saltstack", ".", "com", "/", "en", "/", "latest", "/", "topics", "/", "beacons", "/", "#the", "-", "beacon", "-", "function" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/proxy_example.py#L46-L71
train
saltstack/salt
salt/states/pdbedit.py
absent
def absent(name): ''' Ensure user account is absent name : string username ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} # remove if needed if name in __salt__['pdbedit.list'](False): res = __salt__['pdbedit.delete'](name) if res[name] in ['deleted']: # check if we need to update changes ret['changes'].update(res) elif res[name] not in ['absent']: # oops something went wrong ret['result'] = False else: ret['comment'] = 'account {login} is absent'.format(login=name) return ret
python
def absent(name): ''' Ensure user account is absent name : string username ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} # remove if needed if name in __salt__['pdbedit.list'](False): res = __salt__['pdbedit.delete'](name) if res[name] in ['deleted']: # check if we need to update changes ret['changes'].update(res) elif res[name] not in ['absent']: # oops something went wrong ret['result'] = False else: ret['comment'] = 'account {login} is absent'.format(login=name) return ret
[ "def", "absent", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "# remove if needed", "if", "name", "in", "__salt__", "[", "'pdbedit.list'"...
Ensure user account is absent name : string username
[ "Ensure", "user", "account", "is", "absent" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pdbedit.py#L53-L75
train
saltstack/salt
salt/states/pdbedit.py
managed
def managed(name, **kwargs): ''' Manage user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text domain : string users domain profile : string profile path script : string logon script drive : string home drive homedir : string home directory fullname : string full name account_desc : string account description machine_sid : string specify the machines new primary group SID or rid user_sid : string specify the users new primary group SID or rid account_control : string specify user account control properties .. note:: Only the following can be set: - N: No password required - D: Account disabled - H: Home directory required - L: Automatic Locking - X: Password does not expire reset_login_hours : boolean reset the users allowed logon hours reset_bad_password_count : boolean reset the stored bad login counter ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} # save state saved = __salt__['pdbedit.list'](hashes=True) saved = saved[name] if name in saved else {} # call pdbedit.modify kwargs['login'] = name res = __salt__['pdbedit.modify'](**kwargs) # calculate changes if res[name] in ['created']: ret['changes'] = res elif res[name] in ['updated']: ret['changes'][name] = salt.utils.data.compare_dicts( saved, __salt__['pdbedit.list'](hashes=True)[name], ) elif res[name] not in ['unchanged']: ret['result'] = False ret['comment'] = res[name] return ret
python
def managed(name, **kwargs): ''' Manage user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text domain : string users domain profile : string profile path script : string logon script drive : string home drive homedir : string home directory fullname : string full name account_desc : string account description machine_sid : string specify the machines new primary group SID or rid user_sid : string specify the users new primary group SID or rid account_control : string specify user account control properties .. note:: Only the following can be set: - N: No password required - D: Account disabled - H: Home directory required - L: Automatic Locking - X: Password does not expire reset_login_hours : boolean reset the users allowed logon hours reset_bad_password_count : boolean reset the stored bad login counter ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} # save state saved = __salt__['pdbedit.list'](hashes=True) saved = saved[name] if name in saved else {} # call pdbedit.modify kwargs['login'] = name res = __salt__['pdbedit.modify'](**kwargs) # calculate changes if res[name] in ['created']: ret['changes'] = res elif res[name] in ['updated']: ret['changes'][name] = salt.utils.data.compare_dicts( saved, __salt__['pdbedit.list'](hashes=True)[name], ) elif res[name] not in ['unchanged']: ret['result'] = False ret['comment'] = res[name] return ret
[ "def", "managed", "(", "name", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "# save state", "saved", "=", "__salt__", "["...
Manage user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text domain : string users domain profile : string profile path script : string logon script drive : string home drive homedir : string home directory fullname : string full name account_desc : string account description machine_sid : string specify the machines new primary group SID or rid user_sid : string specify the users new primary group SID or rid account_control : string specify user account control properties .. note:: Only the following can be set: - N: No password required - D: Account disabled - H: Home directory required - L: Automatic Locking - X: Password does not expire reset_login_hours : boolean reset the users allowed logon hours reset_bad_password_count : boolean reset the stored bad login counter
[ "Manage", "user", "account" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pdbedit.py#L78-L146
train
saltstack/salt
salt/modules/salt_proxy.py
_write_proxy_conf
def _write_proxy_conf(proxyfile): ''' write to file ''' msg = 'Invalid value for proxy file provided!, Supplied value = {0}' \ .format(proxyfile) log.trace('Salt Proxy Module: write proxy conf') if proxyfile: log.debug('Writing proxy conf file') with salt.utils.files.fopen(proxyfile, 'w') as proxy_conf: proxy_conf.write(salt.utils.stringutils.to_str('master = {0}' .format(__grains__['master']))) msg = 'Wrote proxy file {0}'.format(proxyfile) log.debug(msg) return msg
python
def _write_proxy_conf(proxyfile): ''' write to file ''' msg = 'Invalid value for proxy file provided!, Supplied value = {0}' \ .format(proxyfile) log.trace('Salt Proxy Module: write proxy conf') if proxyfile: log.debug('Writing proxy conf file') with salt.utils.files.fopen(proxyfile, 'w') as proxy_conf: proxy_conf.write(salt.utils.stringutils.to_str('master = {0}' .format(__grains__['master']))) msg = 'Wrote proxy file {0}'.format(proxyfile) log.debug(msg) return msg
[ "def", "_write_proxy_conf", "(", "proxyfile", ")", ":", "msg", "=", "'Invalid value for proxy file provided!, Supplied value = {0}'", ".", "format", "(", "proxyfile", ")", "log", ".", "trace", "(", "'Salt Proxy Module: write proxy conf'", ")", "if", "proxyfile", ":", "l...
write to file
[ "write", "to", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/salt_proxy.py#L24-L41
train
saltstack/salt
salt/modules/salt_proxy.py
_proxy_conf_file
def _proxy_conf_file(proxyfile, test): ''' Check if proxy conf exists and update ''' changes_old = [] changes_new = [] success = True if not os.path.exists(proxyfile): try: if not test: changes_new.append(_write_proxy_conf(proxyfile)) msg = 'Salt Proxy: Wrote proxy conf {0}'.format(proxyfile) else: msg = 'Salt Proxy: Update required to proxy conf {0}' \ .format(proxyfile) except (OSError, IOError) as err: success = False msg = 'Salt Proxy: Error writing proxy file {0}'.format(err) log.error(msg) changes_new.append(msg) changes_new.append(msg) log.debug(msg) else: msg = 'Salt Proxy: {0} already exists, skipping'.format(proxyfile) changes_old.append(msg) log.debug(msg) return success, changes_new, changes_old
python
def _proxy_conf_file(proxyfile, test): ''' Check if proxy conf exists and update ''' changes_old = [] changes_new = [] success = True if not os.path.exists(proxyfile): try: if not test: changes_new.append(_write_proxy_conf(proxyfile)) msg = 'Salt Proxy: Wrote proxy conf {0}'.format(proxyfile) else: msg = 'Salt Proxy: Update required to proxy conf {0}' \ .format(proxyfile) except (OSError, IOError) as err: success = False msg = 'Salt Proxy: Error writing proxy file {0}'.format(err) log.error(msg) changes_new.append(msg) changes_new.append(msg) log.debug(msg) else: msg = 'Salt Proxy: {0} already exists, skipping'.format(proxyfile) changes_old.append(msg) log.debug(msg) return success, changes_new, changes_old
[ "def", "_proxy_conf_file", "(", "proxyfile", ",", "test", ")", ":", "changes_old", "=", "[", "]", "changes_new", "=", "[", "]", "success", "=", "True", "if", "not", "os", ".", "path", ".", "exists", "(", "proxyfile", ")", ":", "try", ":", "if", "not"...
Check if proxy conf exists and update
[ "Check", "if", "proxy", "conf", "exists", "and", "update" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/salt_proxy.py#L44-L70
train
saltstack/salt
salt/modules/salt_proxy.py
_is_proxy_running
def _is_proxy_running(proxyname): ''' Check if proxy for this name is running ''' cmd = ('ps ax | grep "salt-proxy --proxyid={0}" | grep -v grep' .format(salt.ext.six.moves.shlex_quote(proxyname))) cmdout = __salt__['cmd.run_all']( cmd, timeout=5, python_shell=True) if not cmdout['stdout']: return False else: return True
python
def _is_proxy_running(proxyname): ''' Check if proxy for this name is running ''' cmd = ('ps ax | grep "salt-proxy --proxyid={0}" | grep -v grep' .format(salt.ext.six.moves.shlex_quote(proxyname))) cmdout = __salt__['cmd.run_all']( cmd, timeout=5, python_shell=True) if not cmdout['stdout']: return False else: return True
[ "def", "_is_proxy_running", "(", "proxyname", ")", ":", "cmd", "=", "(", "'ps ax | grep \"salt-proxy --proxyid={0}\" | grep -v grep'", ".", "format", "(", "salt", ".", "ext", ".", "six", ".", "moves", ".", "shlex_quote", "(", "proxyname", ")", ")", ")", "cmdout"...
Check if proxy for this name is running
[ "Check", "if", "proxy", "for", "this", "name", "is", "running" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/salt_proxy.py#L73-L86
train
saltstack/salt
salt/modules/salt_proxy.py
_proxy_process
def _proxy_process(proxyname, test): ''' Check and execute proxy process ''' changes_old = [] changes_new = [] if not _is_proxy_running(proxyname): if not test: __salt__['cmd.run_all']( 'salt-proxy --proxyid={0} -l info -d'.format(salt.ext.six.moves.shlex_quote(proxyname)), timeout=5) changes_new.append('Salt Proxy: Started proxy process for {0}' .format(proxyname)) else: changes_new.append('Salt Proxy: process {0} will be started' .format(proxyname)) else: changes_old.append('Salt Proxy: already running for {0}' .format(proxyname)) return True, changes_new, changes_old
python
def _proxy_process(proxyname, test): ''' Check and execute proxy process ''' changes_old = [] changes_new = [] if not _is_proxy_running(proxyname): if not test: __salt__['cmd.run_all']( 'salt-proxy --proxyid={0} -l info -d'.format(salt.ext.six.moves.shlex_quote(proxyname)), timeout=5) changes_new.append('Salt Proxy: Started proxy process for {0}' .format(proxyname)) else: changes_new.append('Salt Proxy: process {0} will be started' .format(proxyname)) else: changes_old.append('Salt Proxy: already running for {0}' .format(proxyname)) return True, changes_new, changes_old
[ "def", "_proxy_process", "(", "proxyname", ",", "test", ")", ":", "changes_old", "=", "[", "]", "changes_new", "=", "[", "]", "if", "not", "_is_proxy_running", "(", "proxyname", ")", ":", "if", "not", "test", ":", "__salt__", "[", "'cmd.run_all'", "]", "...
Check and execute proxy process
[ "Check", "and", "execute", "proxy", "process" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/salt_proxy.py#L89-L108
train
saltstack/salt
salt/modules/salt_proxy.py
configure_proxy
def configure_proxy(proxyname, start=True): ''' Create the salt proxy file and start the proxy process if required Parameters: proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started default = True CLI Example: .. code-block:: bash salt deviceminion salt_proxy.configure_proxy p8000 ''' changes_new = [] changes_old = [] status_file = True test = __opts__['test'] # write the proxy file if necessary proxyfile = '/etc/salt/proxy' status_file, msg_new, msg_old = _proxy_conf_file(proxyfile, test) changes_new.extend(msg_new) changes_old.extend(msg_old) status_proc = False # start the proxy process if start: status_proc, msg_new, msg_old = _proxy_process(proxyname, test) changes_old.extend(msg_old) changes_new.extend(msg_new) else: changes_old.append('Start is False, not starting salt-proxy process') log.debug('Process not started') return { 'result': status_file and status_proc, 'changes': { 'old': '\n'.join(changes_old), 'new': '\n'.join(changes_new), }, }
python
def configure_proxy(proxyname, start=True): ''' Create the salt proxy file and start the proxy process if required Parameters: proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started default = True CLI Example: .. code-block:: bash salt deviceminion salt_proxy.configure_proxy p8000 ''' changes_new = [] changes_old = [] status_file = True test = __opts__['test'] # write the proxy file if necessary proxyfile = '/etc/salt/proxy' status_file, msg_new, msg_old = _proxy_conf_file(proxyfile, test) changes_new.extend(msg_new) changes_old.extend(msg_old) status_proc = False # start the proxy process if start: status_proc, msg_new, msg_old = _proxy_process(proxyname, test) changes_old.extend(msg_old) changes_new.extend(msg_new) else: changes_old.append('Start is False, not starting salt-proxy process') log.debug('Process not started') return { 'result': status_file and status_proc, 'changes': { 'old': '\n'.join(changes_old), 'new': '\n'.join(changes_new), }, }
[ "def", "configure_proxy", "(", "proxyname", ",", "start", "=", "True", ")", ":", "changes_new", "=", "[", "]", "changes_old", "=", "[", "]", "status_file", "=", "True", "test", "=", "__opts__", "[", "'test'", "]", "# write the proxy file if necessary", "proxyf...
Create the salt proxy file and start the proxy process if required Parameters: proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started default = True CLI Example: .. code-block:: bash salt deviceminion salt_proxy.configure_proxy p8000
[ "Create", "the", "salt", "proxy", "file", "and", "start", "the", "proxy", "process", "if", "required" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/salt_proxy.py#L111-L156
train
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.publish_minions
def publish_minions(self): ''' Publishes minions as a list of dicts. ''' log.debug('in publish minions') minions = {} log.debug('starting loop') for minion, minion_info in six.iteritems(self.minions): log.debug(minion) # log.debug(minion_info) curr_minion = {} curr_minion.update(minion_info) curr_minion.update({'id': minion}) minions[minion] = curr_minion log.debug('ended loop') ret = {'minions': minions} self.handler.write_message( salt.utils.json.dumps(ret) + str('\n\n'))
python
def publish_minions(self): ''' Publishes minions as a list of dicts. ''' log.debug('in publish minions') minions = {} log.debug('starting loop') for minion, minion_info in six.iteritems(self.minions): log.debug(minion) # log.debug(minion_info) curr_minion = {} curr_minion.update(minion_info) curr_minion.update({'id': minion}) minions[minion] = curr_minion log.debug('ended loop') ret = {'minions': minions} self.handler.write_message( salt.utils.json.dumps(ret) + str('\n\n'))
[ "def", "publish_minions", "(", "self", ")", ":", "log", ".", "debug", "(", "'in publish minions'", ")", "minions", "=", "{", "}", "log", ".", "debug", "(", "'starting loop'", ")", "for", "minion", ",", "minion_info", "in", "six", ".", "iteritems", "(", "...
Publishes minions as a list of dicts.
[ "Publishes", "minions", "as", "a", "list", "of", "dicts", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L32-L50
train
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.publish
def publish(self, key, data): ''' Publishes the data to the event stream. ''' publish_data = {key: data} pub = salt.utils.json.dumps(publish_data) + str('\n\n') # future lint: disable=blacklisted-function self.handler.write_message(pub)
python
def publish(self, key, data): ''' Publishes the data to the event stream. ''' publish_data = {key: data} pub = salt.utils.json.dumps(publish_data) + str('\n\n') # future lint: disable=blacklisted-function self.handler.write_message(pub)
[ "def", "publish", "(", "self", ",", "key", ",", "data", ")", ":", "publish_data", "=", "{", "key", ":", "data", "}", "pub", "=", "salt", ".", "utils", ".", "json", ".", "dumps", "(", "publish_data", ")", "+", "str", "(", "'\\n\\n'", ")", "# future ...
Publishes the data to the event stream.
[ "Publishes", "the", "data", "to", "the", "event", "stream", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L52-L58
train
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_minion_update
def process_minion_update(self, event_data): ''' Associate grains data with a minion and publish minion update ''' tag = event_data['tag'] event_info = event_data['data'] mid = tag.split('/')[-1] if not self.minions.get(mid, None): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) log.debug("In process minion grains update with minions=%s", self.minions) self.publish_minions()
python
def process_minion_update(self, event_data): ''' Associate grains data with a minion and publish minion update ''' tag = event_data['tag'] event_info = event_data['data'] mid = tag.split('/')[-1] if not self.minions.get(mid, None): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) log.debug("In process minion grains update with minions=%s", self.minions) self.publish_minions()
[ "def", "process_minion_update", "(", "self", ",", "event_data", ")", ":", "tag", "=", "event_data", "[", "'tag'", "]", "event_info", "=", "event_data", "[", "'data'", "]", "mid", "=", "tag", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "n...
Associate grains data with a minion and publish minion update
[ "Associate", "grains", "data", "with", "a", "minion", "and", "publish", "minion", "update" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L60-L76
train
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_ret_job_event
def process_ret_job_event(self, event_data): ''' Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution. ''' tag = event_data['tag'] event_info = event_data['data'] _, _, jid, _, mid = tag.split('/') job = self.jobs.setdefault(jid, {}) minion = job.setdefault('minions', {}).setdefault(mid, {}) minion.update({'return': event_info['return']}) minion.update({'retcode': event_info['retcode']}) minion.update({'success': event_info['success']}) job_complete = all([minion['success'] for mid, minion in six.iteritems(job['minions'])]) if job_complete: job['state'] = 'complete' self.publish('jobs', self.jobs)
python
def process_ret_job_event(self, event_data): ''' Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution. ''' tag = event_data['tag'] event_info = event_data['data'] _, _, jid, _, mid = tag.split('/') job = self.jobs.setdefault(jid, {}) minion = job.setdefault('minions', {}).setdefault(mid, {}) minion.update({'return': event_info['return']}) minion.update({'retcode': event_info['retcode']}) minion.update({'success': event_info['success']}) job_complete = all([minion['success'] for mid, minion in six.iteritems(job['minions'])]) if job_complete: job['state'] = 'complete' self.publish('jobs', self.jobs)
[ "def", "process_ret_job_event", "(", "self", ",", "event_data", ")", ":", "tag", "=", "event_data", "[", "'tag'", "]", "event_info", "=", "event_data", "[", "'data'", "]", "_", ",", "_", ",", "jid", ",", "_", ",", "mid", "=", "tag", ".", "split", "("...
Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution.
[ "Process", "a", "/", "ret", "event", "returned", "by", "Salt", "for", "a", "particular", "minion", ".", "These", "events", "contain", "the", "returned", "results", "from", "a", "particular", "execution", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L78-L100
train
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_new_job_event
def process_new_job_event(self, event_data): ''' Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted. ''' job = None tag = event_data['tag'] event_info = event_data['data'] minions = {} for mid in event_info['minions']: minions[mid] = {'success': False} job = { 'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, # is a dictionary keyed by mids 'fun': event_info['fun'], 'tgt': event_info['tgt'], 'tgt_type': event_info['tgt_type'], 'state': 'running', } self.jobs[event_info['jid']] = job self.publish('jobs', self.jobs)
python
def process_new_job_event(self, event_data): ''' Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted. ''' job = None tag = event_data['tag'] event_info = event_data['data'] minions = {} for mid in event_info['minions']: minions[mid] = {'success': False} job = { 'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, # is a dictionary keyed by mids 'fun': event_info['fun'], 'tgt': event_info['tgt'], 'tgt_type': event_info['tgt_type'], 'state': 'running', } self.jobs[event_info['jid']] = job self.publish('jobs', self.jobs)
[ "def", "process_new_job_event", "(", "self", ",", "event_data", ")", ":", "job", "=", "None", "tag", "=", "event_data", "[", "'tag'", "]", "event_info", "=", "event_data", "[", "'data'", "]", "minions", "=", "{", "}", "for", "mid", "in", "event_info", "[...
Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted.
[ "Creates", "a", "new", "job", "with", "properties", "from", "the", "event", "data", "like", "jid", "function", "args", "timestamp", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L102-L129
train
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_key_event
def process_key_event(self, event_data): ''' Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True} ''' tag = event_data['tag'] event_info = event_data['data'] if event_info['act'] == 'delete': self.minions.pop(event_info['id'], None) elif event_info['act'] == 'accept': self.minions.setdefault(event_info['id'], {}) self.publish_minions()
python
def process_key_event(self, event_data): ''' Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True} ''' tag = event_data['tag'] event_info = event_data['data'] if event_info['act'] == 'delete': self.minions.pop(event_info['id'], None) elif event_info['act'] == 'accept': self.minions.setdefault(event_info['id'], {}) self.publish_minions()
[ "def", "process_key_event", "(", "self", ",", "event_data", ")", ":", "tag", "=", "event_data", "[", "'tag'", "]", "event_info", "=", "event_data", "[", "'data'", "]", "if", "event_info", "[", "'act'", "]", "==", "'delete'", ":", "self", ".", "minions", ...
Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True}
[ "Tag", ":", "salt", "/", "key", "Data", ":", "{", "_stamp", ":", "2014", "-", "05", "-", "20T22", ":", "45", ":", "04", ".", "345583", "act", ":", "delete", "id", ":", "compute", ".", "home", "result", ":", "True", "}" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L131-L149
train
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_presence_events
def process_presence_events(self, salt_data, token, opts): ''' Check if any minions have connected or dropped. Send a message to the client if they have. ''' log.debug('In presence') changed = False # check if any connections were dropped if set(salt_data['data'].get('lost', [])): dropped_minions = set(salt_data['data'].get('lost', [])) else: dropped_minions = set(self.minions) - set(salt_data['data'].get('present', [])) for minion in dropped_minions: changed = True log.debug('Popping %s', minion) self.minions.pop(minion, None) # check if any new connections were made if set(salt_data['data'].get('new', [])): log.debug('got new minions') new_minions = set(salt_data['data'].get('new', [])) changed = True elif set(salt_data['data'].get('present', [])) - set(self.minions): log.debug('detected new minions') new_minions = set(salt_data['data'].get('present', [])) - set(self.minions) changed = True else: new_minions = [] tgt = ','.join(new_minions) for mid in new_minions: log.debug('Adding minion') self.minions[mid] = {} if tgt: changed = True client = salt.netapi.NetapiClient(opts) client.run( { 'fun': 'grains.items', 'tgt': tgt, 'expr_type': 'list', 'mode': 'client', 'client': 'local', 'asynchronous': 'local_async', 'token': token, }) if changed: self.publish_minions()
python
def process_presence_events(self, salt_data, token, opts): ''' Check if any minions have connected or dropped. Send a message to the client if they have. ''' log.debug('In presence') changed = False # check if any connections were dropped if set(salt_data['data'].get('lost', [])): dropped_minions = set(salt_data['data'].get('lost', [])) else: dropped_minions = set(self.minions) - set(salt_data['data'].get('present', [])) for minion in dropped_minions: changed = True log.debug('Popping %s', minion) self.minions.pop(minion, None) # check if any new connections were made if set(salt_data['data'].get('new', [])): log.debug('got new minions') new_minions = set(salt_data['data'].get('new', [])) changed = True elif set(salt_data['data'].get('present', [])) - set(self.minions): log.debug('detected new minions') new_minions = set(salt_data['data'].get('present', [])) - set(self.minions) changed = True else: new_minions = [] tgt = ','.join(new_minions) for mid in new_minions: log.debug('Adding minion') self.minions[mid] = {} if tgt: changed = True client = salt.netapi.NetapiClient(opts) client.run( { 'fun': 'grains.items', 'tgt': tgt, 'expr_type': 'list', 'mode': 'client', 'client': 'local', 'asynchronous': 'local_async', 'token': token, }) if changed: self.publish_minions()
[ "def", "process_presence_events", "(", "self", ",", "salt_data", ",", "token", ",", "opts", ")", ":", "log", ".", "debug", "(", "'In presence'", ")", "changed", "=", "False", "# check if any connections were dropped", "if", "set", "(", "salt_data", "[", "'data'"...
Check if any minions have connected or dropped. Send a message to the client if they have.
[ "Check", "if", "any", "minions", "have", "connected", "or", "dropped", ".", "Send", "a", "message", "to", "the", "client", "if", "they", "have", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L151-L202
train
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process
def process(self, salt_data, token, opts): ''' Process events and publish data ''' log.debug('In process %s', threading.current_thread()) log.debug(salt_data['tag']) log.debug(salt_data) parts = salt_data['tag'].split('/') if len(parts) < 2: return # TBD: Simplify these conditional expressions if parts[1] == 'job': log.debug('In job part 1') if parts[3] == 'new': log.debug('In new job') self.process_new_job_event(salt_data) # if salt_data['data']['fun'] == 'grains.items': # self.minions = {} elif parts[3] == 'ret': log.debug('In ret') self.process_ret_job_event(salt_data) if salt_data['data']['fun'] == 'grains.items': self.process_minion_update(salt_data) elif parts[1] == 'key': log.debug('In key') self.process_key_event(salt_data) elif parts[1] == 'presence': self.process_presence_events(salt_data, token, opts)
python
def process(self, salt_data, token, opts): ''' Process events and publish data ''' log.debug('In process %s', threading.current_thread()) log.debug(salt_data['tag']) log.debug(salt_data) parts = salt_data['tag'].split('/') if len(parts) < 2: return # TBD: Simplify these conditional expressions if parts[1] == 'job': log.debug('In job part 1') if parts[3] == 'new': log.debug('In new job') self.process_new_job_event(salt_data) # if salt_data['data']['fun'] == 'grains.items': # self.minions = {} elif parts[3] == 'ret': log.debug('In ret') self.process_ret_job_event(salt_data) if salt_data['data']['fun'] == 'grains.items': self.process_minion_update(salt_data) elif parts[1] == 'key': log.debug('In key') self.process_key_event(salt_data) elif parts[1] == 'presence': self.process_presence_events(salt_data, token, opts)
[ "def", "process", "(", "self", ",", "salt_data", ",", "token", ",", "opts", ")", ":", "log", ".", "debug", "(", "'In process %s'", ",", "threading", ".", "current_thread", "(", ")", ")", "log", ".", "debug", "(", "salt_data", "[", "'tag'", "]", ")", ...
Process events and publish data
[ "Process", "events", "and", "publish", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L204-L233
train
saltstack/salt
salt/client/ssh/wrapper/mine.py
get
def get(tgt, fun, tgt_type='glob', roster='flat'): ''' Get data from the mine based on the target, function and tgt_type This will actually run the function on all targeted minions (like publish.publish), as salt-ssh clients can't update the mine themselves. We will look for mine_functions in the roster, pillar, and master config, in that order, looking for a match for the defined function Targets can be matched based on any standard matching system that can be matched on the defined roster (in salt-ssh) via these keywords:: CLI Example: .. code-block:: bash salt-ssh '*' mine.get '*' network.interfaces salt-ssh '*' mine.get 'myminion' network.interfaces roster=flat salt-ssh '*' mine.get '192.168.5.0' network.ipaddrs roster=scan ''' # Set up opts for the SSH object opts = copy.deepcopy(__context__['master_opts']) minopts = copy.deepcopy(__opts__) opts.update(minopts) if roster: opts['roster'] = roster opts['argv'] = [fun] opts['selected_target_option'] = tgt_type opts['tgt'] = tgt opts['arg'] = [] # Create the SSH object to handle the actual call ssh = salt.client.ssh.SSH(opts) # Run salt-ssh to get the minion returns rets = {} for ret in ssh.run_iter(mine=True): rets.update(ret) cret = {} for host in rets: if 'return' in rets[host]: cret[host] = rets[host]['return'] else: cret[host] = rets[host] return cret
python
def get(tgt, fun, tgt_type='glob', roster='flat'): ''' Get data from the mine based on the target, function and tgt_type This will actually run the function on all targeted minions (like publish.publish), as salt-ssh clients can't update the mine themselves. We will look for mine_functions in the roster, pillar, and master config, in that order, looking for a match for the defined function Targets can be matched based on any standard matching system that can be matched on the defined roster (in salt-ssh) via these keywords:: CLI Example: .. code-block:: bash salt-ssh '*' mine.get '*' network.interfaces salt-ssh '*' mine.get 'myminion' network.interfaces roster=flat salt-ssh '*' mine.get '192.168.5.0' network.ipaddrs roster=scan ''' # Set up opts for the SSH object opts = copy.deepcopy(__context__['master_opts']) minopts = copy.deepcopy(__opts__) opts.update(minopts) if roster: opts['roster'] = roster opts['argv'] = [fun] opts['selected_target_option'] = tgt_type opts['tgt'] = tgt opts['arg'] = [] # Create the SSH object to handle the actual call ssh = salt.client.ssh.SSH(opts) # Run salt-ssh to get the minion returns rets = {} for ret in ssh.run_iter(mine=True): rets.update(ret) cret = {} for host in rets: if 'return' in rets[host]: cret[host] = rets[host]['return'] else: cret[host] = rets[host] return cret
[ "def", "get", "(", "tgt", ",", "fun", ",", "tgt_type", "=", "'glob'", ",", "roster", "=", "'flat'", ")", ":", "# Set up opts for the SSH object", "opts", "=", "copy", ".", "deepcopy", "(", "__context__", "[", "'master_opts'", "]", ")", "minopts", "=", "cop...
Get data from the mine based on the target, function and tgt_type This will actually run the function on all targeted minions (like publish.publish), as salt-ssh clients can't update the mine themselves. We will look for mine_functions in the roster, pillar, and master config, in that order, looking for a match for the defined function Targets can be matched based on any standard matching system that can be matched on the defined roster (in salt-ssh) via these keywords:: CLI Example: .. code-block:: bash salt-ssh '*' mine.get '*' network.interfaces salt-ssh '*' mine.get 'myminion' network.interfaces roster=flat salt-ssh '*' mine.get '192.168.5.0' network.ipaddrs roster=scan
[ "Get", "data", "from", "the", "mine", "based", "on", "the", "target", "function", "and", "tgt_type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/mine.py#L17-L63
train
saltstack/salt
salt/utils/timeout.py
wait_for
def wait_for(func, timeout=10, step=1, default=None, func_args=(), func_kwargs=None): ''' Call `func` at regular intervals and Waits until the given function returns a truthy value within the given timeout and returns that value. @param func: @type func: function @param timeout: @type timeout: int | float @param step: Interval at which we should check for the value @type step: int | float @param default: Value that should be returned should `func` not return a truthy value @type default: @param func_args: *args for `func` @type func_args: list | tuple @param func_kwargs: **kwargs for `func` @type func_kwargs: dict @return: `default` or result of `func` ''' if func_kwargs is None: func_kwargs = dict() max_time = time.time() + timeout # Time moves forward so we might not reenter the loop if we step too long step = min(step or 1, timeout) * BLUR_FACTOR ret = default while time.time() <= max_time: call_ret = func(*func_args, **func_kwargs) if call_ret: ret = call_ret break else: time.sleep(step) # Don't allow cases of over-stepping the timeout step = min(step, max_time - time.time()) * BLUR_FACTOR if time.time() > max_time: log.warning("Exceeded waiting time (%s seconds) to exectute %s", timeout, func) return ret
python
def wait_for(func, timeout=10, step=1, default=None, func_args=(), func_kwargs=None): ''' Call `func` at regular intervals and Waits until the given function returns a truthy value within the given timeout and returns that value. @param func: @type func: function @param timeout: @type timeout: int | float @param step: Interval at which we should check for the value @type step: int | float @param default: Value that should be returned should `func` not return a truthy value @type default: @param func_args: *args for `func` @type func_args: list | tuple @param func_kwargs: **kwargs for `func` @type func_kwargs: dict @return: `default` or result of `func` ''' if func_kwargs is None: func_kwargs = dict() max_time = time.time() + timeout # Time moves forward so we might not reenter the loop if we step too long step = min(step or 1, timeout) * BLUR_FACTOR ret = default while time.time() <= max_time: call_ret = func(*func_args, **func_kwargs) if call_ret: ret = call_ret break else: time.sleep(step) # Don't allow cases of over-stepping the timeout step = min(step, max_time - time.time()) * BLUR_FACTOR if time.time() > max_time: log.warning("Exceeded waiting time (%s seconds) to exectute %s", timeout, func) return ret
[ "def", "wait_for", "(", "func", ",", "timeout", "=", "10", ",", "step", "=", "1", ",", "default", "=", "None", ",", "func_args", "=", "(", ")", ",", "func_kwargs", "=", "None", ")", ":", "if", "func_kwargs", "is", "None", ":", "func_kwargs", "=", "...
Call `func` at regular intervals and Waits until the given function returns a truthy value within the given timeout and returns that value. @param func: @type func: function @param timeout: @type timeout: int | float @param step: Interval at which we should check for the value @type step: int | float @param default: Value that should be returned should `func` not return a truthy value @type default: @param func_args: *args for `func` @type func_args: list | tuple @param func_kwargs: **kwargs for `func` @type func_kwargs: dict @return: `default` or result of `func`
[ "Call", "func", "at", "regular", "intervals", "and", "Waits", "until", "the", "given", "function", "returns", "a", "truthy", "value", "within", "the", "given", "timeout", "and", "returns", "that", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/timeout.py#L12-L50
train
saltstack/salt
salt/modules/debian_service.py
get_enabled
def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' prefix = '/etc/rc[S{0}].d/S'.format(_get_runlevel()) ret = set() lines = glob.glob('{0}*'.format(prefix)) for line in lines: ret.add(re.split(prefix + r'\d+', line)[1]) return sorted(ret)
python
def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' prefix = '/etc/rc[S{0}].d/S'.format(_get_runlevel()) ret = set() lines = glob.glob('{0}*'.format(prefix)) for line in lines: ret.add(re.split(prefix + r'\d+', line)[1]) return sorted(ret)
[ "def", "get_enabled", "(", ")", ":", "prefix", "=", "'/etc/rc[S{0}].d/S'", ".", "format", "(", "_get_runlevel", "(", ")", ")", "ret", "=", "set", "(", ")", "lines", "=", "glob", ".", "glob", "(", "'{0}*'", ".", "format", "(", "prefix", ")", ")", "for...
Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled
[ "Return", "a", "list", "of", "service", "that", "are", "enabled", "on", "boot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_service.py#L76-L91
train
saltstack/salt
salt/modules/debian_service.py
get_all
def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = set() lines = glob.glob('/etc/init.d/*') for line in lines: service = line.split('/etc/init.d/')[1] # Remove README. If it's an enabled service, it will be added back in. if service != 'README': ret.add(service) return sorted(ret | set(get_enabled()))
python
def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = set() lines = glob.glob('/etc/init.d/*') for line in lines: service = line.split('/etc/init.d/')[1] # Remove README. If it's an enabled service, it will be added back in. if service != 'README': ret.add(service) return sorted(ret | set(get_enabled()))
[ "def", "get_all", "(", ")", ":", "ret", "=", "set", "(", ")", "lines", "=", "glob", ".", "glob", "(", "'/etc/init.d/*'", ")", "for", "line", "in", "lines", ":", "service", "=", "line", ".", "split", "(", "'/etc/init.d/'", ")", "[", "1", "]", "# Rem...
Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all
[ "Return", "all", "available", "boot", "services" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_service.py#L136-L153
train
saltstack/salt
salt/modules/debian_service.py
enable
def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} defaults 99'.format(_cmd_quote(name)) else: cmd = 'update-rc.d {0} enable'.format(_cmd_quote(name)) try: if int(osmajor) >= 6: cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd except ValueError: osrel = _osrel() if osrel == 'testing/unstable' or osrel == 'unstable' or osrel.endswith("/sid"): cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd return not __salt__['cmd.retcode'](cmd, python_shell=True)
python
def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} defaults 99'.format(_cmd_quote(name)) else: cmd = 'update-rc.d {0} enable'.format(_cmd_quote(name)) try: if int(osmajor) >= 6: cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd except ValueError: osrel = _osrel() if osrel == 'testing/unstable' or osrel == 'unstable' or osrel.endswith("/sid"): cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd return not __salt__['cmd.retcode'](cmd, python_shell=True)
[ "def", "enable", "(", "name", ",", "*", "*", "kwargs", ")", ":", "osmajor", "=", "_osrel", "(", ")", "[", "0", "]", "if", "osmajor", "<", "'6'", ":", "cmd", "=", "'update-rc.d -f {0} defaults 99'", ".", "format", "(", "_cmd_quote", "(", "name", ")", ...
Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name>
[ "Enable", "the", "named", "service", "to", "start", "at", "boot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_service.py#L273-L295
train