repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
start
|
python
|
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
|
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L495-L518
|
[
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def _get_node(name):\n attempts = 5\n while attempts >= 0:\n try:\n return list_nodes_full()[name]\n except KeyError:\n attempts -= 1\n log.debug(\n 'Failed to get the data for node \\'%s\\'. Remaining '\n 'attempts: %s', name, attempts\n )\n # Just a little delay between attempts...\n time.sleep(0.5)\n raise SaltCloudNotFound(\n 'The specified instance {0} not found'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
stop
|
python
|
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
|
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L521-L548
|
[
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def _get_node(name):\n attempts = 5\n while attempts >= 0:\n try:\n return list_nodes_full()[name]\n except KeyError:\n attempts -= 1\n log.debug(\n 'Failed to get the data for node \\'%s\\'. Remaining '\n 'attempts: %s', name, attempts\n )\n # Just a little delay between attempts...\n time.sleep(0.5)\n raise SaltCloudNotFound(\n 'The specified instance {0} not found'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
reboot
|
python
|
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
|
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L551-L574
|
[
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def _get_node(name):\n attempts = 5\n while attempts >= 0:\n try:\n return list_nodes_full()[name]\n except KeyError:\n attempts -= 1\n log.debug(\n 'Failed to get the data for node \\'%s\\'. Remaining '\n 'attempts: %s', name, attempts\n )\n # Just a little delay between attempts...\n time.sleep(0.5)\n raise SaltCloudNotFound(\n 'The specified instance {0} not found'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
create_node
|
python
|
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
|
Convenience function to make the rest api call for node creation.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L577-L608
|
[
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
create
|
python
|
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
|
Create a single VM from a data dict
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L611-L741
|
[
"def destroy(name, call=None):\n '''\n Destroy a node.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a destroy myinstance\n salt-cloud -d myinstance\n '''\n if call == 'function':\n raise SaltCloudSystemExit(\n 'The destroy action must be called with -d, --destroy, '\n '-a or --action.'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroying instance',\n 'salt/cloud/{0}/destroying'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n instanceId = _get_node(name)['InstanceId']\n\n # have to stop instance before del it\n stop_params = {\n 'Action': 'StopInstance',\n 'InstanceId': instanceId\n }\n query(stop_params)\n\n params = {\n 'Action': 'DeleteInstance',\n 'InstanceId': instanceId\n }\n\n node = query(params)\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroyed instance',\n 'salt/cloud/{0}/destroyed'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n return node\n",
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def is_profile_configured(opts, provider, profile_name, vm_=None):\n '''\n Check if the requested profile contains the minimum required parameters for\n a profile.\n\n Required parameters include image and provider for all drivers, while some\n drivers also require size keys.\n\n .. versionadded:: 2015.8.0\n '''\n # Standard dict keys required by all drivers.\n required_keys = ['provider']\n alias, driver = provider.split(':')\n\n # Most drivers need an image to be specified, but some do not.\n non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']\n\n # Most drivers need a size, but some do not.\n non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',\n 'softlayer', 'softlayer_hw', 'vmware', 'vsphere',\n 'virtualbox', 'libvirt', 'oneandone', 'profitbricks']\n\n provider_key = opts['providers'][alias][driver]\n profile_key = opts['providers'][alias][driver]['profiles'][profile_name]\n\n # If cloning on Linode, size and image are not necessary.\n # They are obtained from the to-be-cloned VM.\n if driver == 'linode' and profile_key.get('clonefrom', False):\n non_image_drivers.append('linode')\n non_size_drivers.append('linode')\n elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):\n non_image_drivers.append('gce')\n\n # If cloning on VMware, specifying image is not necessary.\n if driver == 'vmware' and 'image' not in list(profile_key.keys()):\n non_image_drivers.append('vmware')\n\n if driver not in non_image_drivers:\n required_keys.append('image')\n if driver == 'vmware':\n required_keys.append('datastore')\n elif driver in ['linode', 'virtualbox']:\n required_keys.append('clonefrom')\n elif driver == 'nova':\n nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']\n if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):\n required_keys.extend(nova_image_keys)\n\n if driver not in non_size_drivers:\n required_keys.append('size')\n\n # Check if required fields are supplied in the provider config. If they\n # are present, remove it from the required_keys list.\n for item in list(required_keys):\n if item in provider_key:\n required_keys.remove(item)\n\n # If a vm_ dict was passed in, use that information to get any other configs\n # that we might have missed thus far, such as a option provided in a map file.\n if vm_:\n for item in list(required_keys):\n if item in vm_:\n required_keys.remove(item)\n\n # Check for remaining required parameters in the profile config.\n for item in required_keys:\n if profile_key.get(item, None) is None:\n # There's at least one required configuration item which is not set.\n log.error(\n \"The required '%s' configuration setting is missing from \"\n \"the '%s' profile, which is configured under the '%s' alias.\",\n item, profile_name, alias\n )\n return False\n\n return True\n",
"def get_image(vm_):\n '''\n Return the image object to use\n '''\n images = avail_images()\n vm_image = six.text_type(config.get_cloud_config_value(\n 'image', vm_, __opts__, search_global=False\n ))\n\n if not vm_image:\n raise SaltCloudNotFound('No image specified for this VM.')\n\n if vm_image and six.text_type(vm_image) in images:\n return images[vm_image]['ImageId']\n raise SaltCloudNotFound(\n 'The specified image, \\'{0}\\', could not be found.'.format(vm_image)\n )\n",
"def get_securitygroup(vm_):\n '''\n Return the security group\n '''\n sgs = list_securitygroup()\n securitygroup = config.get_cloud_config_value(\n 'securitygroup', vm_, __opts__, search_global=False\n )\n\n if not securitygroup:\n raise SaltCloudNotFound('No securitygroup ID specified for this VM.')\n\n if securitygroup and six.text_type(securitygroup) in sgs:\n return sgs[securitygroup]['SecurityGroupId']\n raise SaltCloudNotFound(\n 'The specified security group, \\'{0}\\', could not be found.'.format(\n securitygroup)\n )\n",
"def get_size(vm_):\n '''\n Return the VM's size. Used by create_node().\n '''\n sizes = avail_sizes()\n vm_size = six.text_type(config.get_cloud_config_value(\n 'size', vm_, __opts__, search_global=False\n ))\n\n if not vm_size:\n raise SaltCloudNotFound('No size specified for this VM.')\n\n if vm_size and six.text_type(vm_size) in sizes:\n return sizes[vm_size]['InstanceTypeId']\n\n raise SaltCloudNotFound(\n 'The specified size, \\'{0}\\', could not be found.'.format(vm_size)\n )\n",
"def __get_location(vm_):\n '''\n Return the VM's location\n '''\n locations = avail_locations()\n vm_location = six.text_type(config.get_cloud_config_value(\n 'location', vm_, __opts__, search_global=False\n ))\n\n if not vm_location:\n raise SaltCloudNotFound('No location specified for this VM.')\n\n if vm_location and six.text_type(vm_location) in locations:\n return locations[vm_location]['RegionId']\n raise SaltCloudNotFound(\n 'The specified location, \\'{0}\\', could not be found.'.format(\n vm_location\n )\n )\n",
"def create_node(kwargs):\n '''\n Convenience function to make the rest api call for node creation.\n '''\n if not isinstance(kwargs, dict):\n kwargs = {}\n\n # Required parameters\n params = {\n 'Action': 'CreateInstance',\n 'InstanceType': kwargs.get('size_id', ''),\n 'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),\n 'ImageId': kwargs.get('image_id', ''),\n 'SecurityGroupId': kwargs.get('securitygroup_id', ''),\n 'InstanceName': kwargs.get('name', ''),\n }\n\n # Optional parameters'\n optional = [\n 'InstanceName', 'InternetChargeType',\n 'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',\n 'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'\n # 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'\n ]\n\n for item in optional:\n if item in kwargs:\n params.update({item: kwargs[item]})\n\n # invoke web call\n result = query(params)\n return result['InstanceId']\n",
"def wait_for_ip(update_callback,\n update_args=None,\n update_kwargs=None,\n timeout=5 * 60,\n interval=5,\n interval_multiplier=1,\n max_failures=10):\n '''\n Helper function that waits for an IP address for a specific maximum amount\n of time.\n\n :param update_callback: callback function which queries the cloud provider\n for the VM ip address. It must return None if the\n required data, IP included, is not available yet.\n :param update_args: Arguments to pass to update_callback\n :param update_kwargs: Keyword arguments to pass to update_callback\n :param timeout: The maximum amount of time(in seconds) to wait for the IP\n address.\n :param interval: The looping interval, i.e., the amount of time to sleep\n before the next iteration.\n :param interval_multiplier: Increase the interval by this multiplier after\n each request; helps with throttling\n :param max_failures: If update_callback returns ``False`` it's considered\n query failure. This value is the amount of failures\n accepted before giving up.\n :returns: The update_callback returned data\n :raises: SaltCloudExecutionTimeout\n\n '''\n if update_args is None:\n update_args = ()\n if update_kwargs is None:\n update_kwargs = {}\n\n duration = timeout\n while True:\n log.debug(\n 'Waiting for VM IP. Giving up in 00:%02d:%02d.',\n int(timeout // 60), int(timeout % 60)\n )\n data = update_callback(*update_args, **update_kwargs)\n if data is False:\n log.debug(\n '\\'update_callback\\' has returned \\'False\\', which is '\n 'considered a failure. Remaining Failures: %s.', max_failures\n )\n max_failures -= 1\n if max_failures <= 0:\n raise SaltCloudExecutionFailure(\n 'Too many failures occurred while waiting for '\n 'the IP address.'\n )\n elif data is not None:\n return data\n\n if timeout < 0:\n raise SaltCloudExecutionTimeout(\n 'Unable to get IP for 00:{0:02d}:{1:02d}.'.format(\n int(duration // 60),\n int(duration % 60)\n )\n )\n time.sleep(interval)\n timeout -= interval\n\n if interval_multiplier > 1:\n interval *= interval_multiplier\n if interval > timeout:\n interval = timeout + 1\n log.info('Interval multiplier in effect; interval is '\n 'now %ss.', interval)\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
_compute_signature
|
python
|
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
|
Generate aliyun request signature
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L744-L776
| null |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
query
|
python
|
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
|
Make a web call to aliyun ECS REST API
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L779-L832
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('id', 'key')\n )\n",
"def _compute_signature(parameters, access_key_secret):\n '''\n Generate aliyun request signature\n '''\n\n def percent_encode(line):\n if not isinstance(line, six.string_types):\n return line\n\n s = line\n if sys.stdin.encoding is None:\n s = line.decode().encode('utf8')\n else:\n s = line.decode(sys.stdin.encoding).encode('utf8')\n res = _quote(s, '')\n res = res.replace('+', '%20')\n res = res.replace('*', '%2A')\n res = res.replace('%7E', '~')\n return res\n\n sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])\n\n canonicalizedQueryString = ''\n for k, v in sortedParameters:\n canonicalizedQueryString += '&' + percent_encode(k) \\\n + '=' + percent_encode(v)\n\n # All aliyun API only support GET method\n stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])\n\n h = hmac.new(to_bytes(access_key_secret + \"&\"), stringToSign, sha1)\n signature = base64.encodestring(h.digest()).strip()\n return signature\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
show_disk
|
python
|
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
|
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L850-L877
|
[
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
list_monitor_data
|
python
|
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
|
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L880-L917
|
[
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def get_location(vm_=None):\n '''\n Return the aliyun region to use, in this order:\n - CLI parameter\n - VM parameter\n - Cloud profile setting\n '''\n return __opts__.get(\n 'location',\n config.get_cloud_config_value(\n 'location',\n vm_ or get_configured_provider(),\n __opts__,\n default=DEFAULT_LOCATION,\n search_global=False\n )\n )\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
show_image
|
python
|
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
|
Show the details from aliyun image
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L950-L991
|
[
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def get_location(vm_=None):\n '''\n Return the aliyun region to use, in this order:\n - CLI parameter\n - VM parameter\n - Cloud profile setting\n '''\n return __opts__.get(\n 'location',\n config.get_cloud_config_value(\n 'location',\n vm_ or get_configured_provider(),\n __opts__,\n default=DEFAULT_LOCATION,\n search_global=False\n )\n )\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
saltstack/salt
|
salt/cloud/clouds/aliyun.py
|
destroy
|
python
|
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
instanceId = _get_node(name)['InstanceId']
# have to stop instance before del it
stop_params = {
'Action': 'StopInstance',
'InstanceId': instanceId
}
query(stop_params)
params = {
'Action': 'DeleteInstance',
'InstanceId': instanceId
}
node = query(params)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return node
|
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud -a destroy myinstance
salt-cloud -d myinstance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L994-L1045
|
[
"def query(params=None):\n '''\n Make a web call to aliyun ECS REST API\n '''\n path = 'https://ecs-cn-hangzhou.aliyuncs.com'\n\n access_key_id = config.get_cloud_config_value(\n 'id', get_configured_provider(), __opts__, search_global=False\n )\n access_key_secret = config.get_cloud_config_value(\n 'key', get_configured_provider(), __opts__, search_global=False\n )\n\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n # public interface parameters\n parameters = {\n 'Format': 'JSON',\n 'Version': DEFAULT_ALIYUN_API_VERSION,\n 'AccessKeyId': access_key_id,\n 'SignatureVersion': '1.0',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureNonce': six.text_type(uuid.uuid1()),\n 'TimeStamp': timestamp,\n }\n\n # include action or function parameters\n if params:\n parameters.update(params)\n\n # Calculate the string for Signature\n signature = _compute_signature(parameters, access_key_secret)\n parameters['Signature'] = signature\n\n request = requests.get(path, params=parameters, verify=True)\n if request.status_code != 200:\n raise SaltCloudSystemExit(\n 'An error occurred while querying aliyun ECS. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n request.text\n )\n )\n\n log.debug(request.url)\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if 'Code' in result:\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('Message', {}))\n )\n return result\n",
"def _get_node(name):\n attempts = 5\n while attempts >= 0:\n try:\n return list_nodes_full()[name]\n except KeyError:\n attempts -= 1\n log.debug(\n 'Failed to get the data for node \\'%s\\'. Remaining '\n 'attempts: %s', name, attempts\n )\n # Just a little delay between attempts...\n time.sleep(0.5)\n raise SaltCloudNotFound(\n 'The specified instance {0} not found'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/aliyun.conf``:
.. code-block:: yaml
my-aliyun-config:
# aliyun Access Key ID
id: wFGEwgregeqw3435gDger
# aliyun Access Key Secret
key: GDE43t43REGTrkilg43934t34qT43t4dgegerGEgg
location: cn-qingdao
driver: aliyun
:depends: requests
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import pprint
import logging
import hmac
import uuid
import sys
import base64
from hashlib import sha1
# Import Salt libs
from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: disable=import-error,no-name-in-module
# Import salt cloud libs
import salt.utils.cloud
import salt.utils.data
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.utils.stringutils import to_bytes
# Import 3rd-party libs
from salt.ext import six
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
ALIYUN_LOCATIONS = {
# 'us-west-2': 'ec2_us_west_oregon',
'cn-hangzhou': 'AliYun HangZhou Region',
'cn-beijing': 'AliYun BeiJing Region',
'cn-hongkong': 'AliYun HongKong Region',
'cn-qingdao': 'AliYun QingDao Region',
'cn-shanghai': 'AliYun ShangHai Region',
'cn-shenzhen': 'AliYun ShenZheng Region',
'ap-northeast-1': 'AliYun DongJing Region',
'ap-southeast-1': 'AliYun XinJiaPo Region',
'ap-southeast-2': 'AliYun XiNi Region',
'eu-central-1': 'EU FalaKeFu Region',
'me-east-1': 'ME DiBai Region',
'us-east-1': 'US FuJiNiYa Region',
'us-west-1': 'US GuiGu Region',
}
DEFAULT_LOCATION = 'cn-hangzhou'
DEFAULT_ALIYUN_API_VERSION = '2014-05-26'
__virtualname__ = 'aliyun'
# Only load in this module if the aliyun configurations are in place
def __virtual__():
'''
Check for aliyun configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = six.text_type(region[item])
return ret
def avail_images(kwargs=None, call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
provider = get_configured_provider()
location = provider.get('location', DEFAULT_LOCATION)
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'PageSize': '100',
}
items = query(params=params)
ret = {}
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
params = {'Action': 'DescribeInstanceTypes'}
items = query(params=params)
ret = {}
for image in items['InstanceTypes']['InstanceType']:
ret[image['InstanceTypeId']] = {}
for item in image:
ret[image['InstanceTypeId']][item] = six.text_type(image[item])
return ret
def get_location(vm_=None):
'''
Return the aliyun region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for item in zone:
ret[zone['ZoneId']][item] = six.text_type(zone[item])
return ret
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
}
nodes = query(params)
log.debug(
'Total %s instance found in Region %s',
nodes['TotalCount'], location
)
if 'Code' in nodes or nodes['TotalCount'] == 0:
return ret
for node in nodes['InstanceStatuses']['InstanceStatus']:
ret[node['InstanceId']] = {}
for item in node:
ret[node['InstanceId']][item] = node[item]
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
nodes = list_nodes_full()
ret = {}
for instanceId in nodes:
node = nodes[instanceId]
ret[node['name']] = {
'id': node['id'],
'name': node['name'],
'public_ips': node['public_ips'],
'private_ips': node['private_ips'],
'size': node['size'],
'state': six.text_type(node['state']),
}
return ret
def list_nodes_full(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f '
'or --function.'
)
ret = {}
location = get_location()
params = {
'Action': 'DescribeInstanceStatus',
'RegionId': location,
'PageSize': '50'
}
result = query(params=params)
log.debug(
'Total %s instance found in Region %s',
result['TotalCount'], location
)
if 'Code' in result or result['TotalCount'] == 0:
return ret
# aliyun max 100 top instance in api
result_instancestatus = result['InstanceStatuses']['InstanceStatus']
if result['TotalCount'] > 50:
params['PageNumber'] = '2'
result = query(params=params)
result_instancestatus.update(result['InstanceStatuses']['InstanceStatus'])
for node in result_instancestatus:
instanceId = node.get('InstanceId', '')
params = {
'Action': 'DescribeInstanceAttribute',
'InstanceId': instanceId
}
items = query(params=params)
if 'Code' in items:
log.warning('Query instance:%s attribute failed', instanceId)
continue
name = items['InstanceName']
ret[name] = {
'id': items['InstanceId'],
'name': name,
'image': items['ImageId'],
'size': 'TODO',
'state': items['Status']
}
for item in items:
value = items[item]
if value is not None:
value = six.text_type(value)
if item == "PublicIpAddress":
ret[name]['public_ips'] = items[item]['IpAddress']
if item == "InnerIpAddress" and 'private_ips' not in ret[name]:
ret[name]['private_ips'] = items[item]['IpAddress']
if item == 'VpcAttributes':
vpc_ips = items[item]['PrivateIpAddress']['IpAddress']
if vpc_ips:
ret[name]['private_ips'] = vpc_ips
ret[name][item] = value
provider = __active_provider_name__ or 'aliyun'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
__opts__['update_cachedir'] = True
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_location(),
'PageSize': '50',
}
result = query(params)
if 'Code' in result:
return {}
ret = {}
for sg in result['SecurityGroups']['SecurityGroup']:
ret[sg['SecurityGroupId']] = {}
for item in sg:
ret[sg['SecurityGroupId']][item] = sg[item]
return ret
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = six.text_type(config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
))
if not vm_image:
raise SaltCloudNotFound('No image specified for this VM.')
if vm_image and six.text_type(vm_image) in images:
return images[vm_image]['ImageId']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
if not vm_size:
raise SaltCloudNotFound('No size specified for this VM.')
if vm_size and six.text_type(vm_size) in sizes:
return sizes[vm_size]['InstanceTypeId']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def __get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
if not vm_location:
raise SaltCloudNotFound('No location specified for this VM.')
if vm_location and six.text_type(vm_location) in locations:
return locations[vm_location]['RegionId']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {'Action': 'StartInstance',
'InstanceId': instanceId}
result = query(params)
return result
def stop(name, force=False, call=None):
'''
Stop a node
CLI Examples:
.. code-block:: bash
salt-cloud -a stop myinstance
salt-cloud -a stop myinstance force=True
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instanceId = _get_node(name)['InstanceId']
params = {
'Action': 'StopInstance',
'InstanceId': instanceId,
'ForceStop': six.text_type(force).lower()
}
result = query(params)
return result
def reboot(name, call=None):
'''
Reboot a node
CLI Examples:
.. code-block:: bash
salt-cloud -a reboot myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
instance_id = _get_node(name)['InstanceId']
params = {'Action': 'RebootInstance',
'InstanceId': instance_id}
result = query(params)
return result
def create_node(kwargs):
'''
Convenience function to make the rest api call for node creation.
'''
if not isinstance(kwargs, dict):
kwargs = {}
# Required parameters
params = {
'Action': 'CreateInstance',
'InstanceType': kwargs.get('size_id', ''),
'RegionId': kwargs.get('region_id', DEFAULT_LOCATION),
'ImageId': kwargs.get('image_id', ''),
'SecurityGroupId': kwargs.get('securitygroup_id', ''),
'InstanceName': kwargs.get('name', ''),
}
# Optional parameters'
optional = [
'InstanceName', 'InternetChargeType',
'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut',
'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId'
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
]
for item in optional:
if item in kwargs:
params.update({item: kwargs[item]})
# invoke web call
result = query(params)
return result['InstanceId']
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'aliyun',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size_id': get_size(vm_),
'image_id': get_image(vm_),
'region_id': __get_location(vm_),
'securitygroup_id': get_securitygroup(vm_),
}
if 'vswitch_id' in vm_:
kwargs['VSwitchId'] = vm_['vswitch_id']
if 'internet_chargetype' in vm_:
kwargs['InternetChargeType'] = vm_['internet_chargetype']
if 'internet_maxbandwidthin' in vm_:
kwargs['InternetMaxBandwidthIn'] = six.text_type(vm_['internet_maxbandwidthin'])
if 'internet_maxbandwidthout' in vm_:
kwargs['InternetMaxBandwidthOut'] = six.text_type(vm_['internet_maxbandwidthOut'])
if 'hostname' in vm_:
kwargs['HostName'] = vm_['hostname']
if 'password' in vm_:
kwargs['Password'] = vm_['password']
if 'instance_name' in vm_:
kwargs['InstanceName'] = vm_['instance_name']
if 'systemdisk_category' in vm_:
kwargs['SystemDisk.Category'] = vm_['systemdisk_category']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Aliyun ECS\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], six.text_type(exc),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
# repair ip address error and start vm
time.sleep(8)
params = {'Action': 'StartInstance',
'InstanceId': ret}
query(params)
def __query_node_data(vm_name):
data = show_instance(vm_name, call='action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data.get('PublicIpAddress', None) is not None:
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if data['public_ips']:
ssh_ip = data['public_ips'][0]
elif data['private_ips']:
ssh_ip = data['private_ips'][0]
else:
log.info('No available ip:cant connect to salt')
return False
log.debug('VM %s is now running', ssh_ip)
vm_['ssh_host'] = ssh_ip
# The instance is booted and accessible, let's Salt it!
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def _compute_signature(parameters, access_key_secret):
'''
Generate aliyun request signature
'''
def percent_encode(line):
if not isinstance(line, six.string_types):
return line
s = line
if sys.stdin.encoding is None:
s = line.decode().encode('utf8')
else:
s = line.decode(sys.stdin.encoding).encode('utf8')
res = _quote(s, '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])
canonicalizedQueryString = ''
for k, v in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) \
+ '=' + percent_encode(v)
# All aliyun API only support GET method
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def query(params=None):
'''
Make a web call to aliyun ECS REST API
'''
path = 'https://ecs-cn-hangzhou.aliyuncs.com'
access_key_id = config.get_cloud_config_value(
'id', get_configured_provider(), __opts__, search_global=False
)
access_key_secret = config.get_cloud_config_value(
'key', get_configured_provider(), __opts__, search_global=False
)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# public interface parameters
parameters = {
'Format': 'JSON',
'Version': DEFAULT_ALIYUN_API_VERSION,
'AccessKeyId': access_key_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': six.text_type(uuid.uuid1()),
'TimeStamp': timestamp,
}
# include action or function parameters
if params:
parameters.update(params)
# Calculate the string for Signature
signature = _compute_signature(parameters, access_key_secret)
parameters['Signature'] = signature
request = requests.get(path, params=parameters, verify=True)
if request.status_code != 200:
raise SaltCloudSystemExit(
'An error occurred while querying aliyun ECS. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
request.text
)
)
log.debug(request.url)
content = request.text
result = salt.utils.json.loads(content)
if 'Code' in result:
raise SaltCloudSystemExit(
pprint.pformat(result.get('Message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
)
ret = {}
params = {
'Action': 'DescribeInstanceDisks',
'InstanceId': name
}
items = query(params=params)
for disk in items['Disks']['Disk']:
ret[disk['DiskId']] = {}
for item in disk:
ret[disk['DiskId']][item] = six.text_type(disk[item])
return ret
def list_monitor_data(kwargs=None, call=None):
'''
Get monitor data of the instance. If instance name is
missing, will show all the instance monitor data on the region.
CLI Examples:
.. code-block:: bash
salt-cloud -f list_monitor_data aliyun
salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_monitor_data must be called with -f or --function.'
)
if not isinstance(kwargs, dict):
kwargs = {}
ret = {}
params = {
'Action': 'GetMonitorData',
'RegionId': get_location()
}
if 'name' in kwargs:
params['InstanceId'] = kwargs['name']
items = query(params=params)
monitorData = items['MonitorData']
for data in monitorData['InstanceMonitorData']:
ret[data['InstanceId']] = {}
for item in data:
ret[data['InstanceId']][item] = six.text_type(data[item])
return ret
def show_instance(name, call=None):
'''
Show the details from aliyun instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
return _get_node(name)
def _get_node(name):
attempts = 5
while attempts >= 0:
try:
return list_nodes_full()[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
raise SaltCloudNotFound(
'The specified instance {0} not found'.format(name)
)
def show_image(kwargs, call=None):
'''
Show the details from aliyun image
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_images function must be called with '
'-f or --function'
)
if not isinstance(kwargs, dict):
kwargs = {}
location = get_location()
if 'location' in kwargs:
location = kwargs['location']
params = {
'Action': 'DescribeImages',
'RegionId': location,
'ImageId': kwargs['image']
}
ret = {}
items = query(params=params)
# DescribeImages so far support input multi-image. And
# if not found certain image, the response will include
# blank image list other than 'not found' error message
if 'Code' in items or not items['Images']['Image']:
raise SaltCloudNotFound('The specified image could not be found.')
log.debug(
'Total %s image found in Region %s',
items['TotalCount'], location
)
for image in items['Images']['Image']:
ret[image['ImageId']] = {}
for item in image:
ret[image['ImageId']][item] = six.text_type(image[item])
return ret
|
saltstack/salt
|
salt/modules/solarispkg.py
|
_write_adminfile
|
python
|
def _write_adminfile(kwargs):
'''
Create a temporary adminfile based on the keyword arguments passed to
pkg.install.
'''
# Set the adminfile default variables
email = kwargs.get('email', '')
instance = kwargs.get('instance', 'quit')
partial = kwargs.get('partial', 'nocheck')
runlevel = kwargs.get('runlevel', 'nocheck')
idepend = kwargs.get('idepend', 'nocheck')
rdepend = kwargs.get('rdepend', 'nocheck')
space = kwargs.get('space', 'nocheck')
setuid = kwargs.get('setuid', 'nocheck')
conflict = kwargs.get('conflict', 'nocheck')
action = kwargs.get('action', 'nocheck')
basedir = kwargs.get('basedir', 'default')
# Make tempfile to hold the adminfile contents.
adminfile = salt.utils.files.mkstemp(prefix="salt-")
def _write_line(fp_, line):
fp_.write(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(adminfile, 'w') as fp_:
_write_line(fp_, 'email={0}\n'.format(email))
_write_line(fp_, 'instance={0}\n'.format(instance))
_write_line(fp_, 'partial={0}\n'.format(partial))
_write_line(fp_, 'runlevel={0}\n'.format(runlevel))
_write_line(fp_, 'idepend={0}\n'.format(idepend))
_write_line(fp_, 'rdepend={0}\n'.format(rdepend))
_write_line(fp_, 'space={0}\n'.format(space))
_write_line(fp_, 'setuid={0}\n'.format(setuid))
_write_line(fp_, 'conflict={0}\n'.format(conflict))
_write_line(fp_, 'action={0}\n'.format(action))
_write_line(fp_, 'basedir={0}\n'.format(basedir))
return adminfile
|
Create a temporary adminfile based on the keyword arguments passed to
pkg.install.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solarispkg.py#L42-L79
| null |
# -*- coding: utf-8 -*-
'''
Package support for Solaris
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import logging
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, MinionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Solaris
'''
if __grains__['os_family'] == 'Solaris' and float(__grains__['kernelrelease']) <= 5.10:
return __virtualname__
return (False,
'The solarispkg execution module failed to load: only available '
'on Solaris <= 10.')
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict:
.. code-block:: python
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {}
cmd = '/usr/bin/pkginfo -x'
# Package information returned two lines per package. On even-offset
# lines, the package name is in the first column. On odd-offset lines, the
# package version is in the second column.
lines = __salt__['cmd.run'](
cmd,
output_loglevel='trace',
python_shell=False).splitlines()
for index, line in enumerate(lines):
if index % 2 == 0:
name = line.split()[0].strip()
if index % 2 == 1:
version_num = line.split()[1].strip()
__salt__['pkg_resource.add_pkg'](ret, name, version_num)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
NOTE: As package repositories are not presently supported for Solaris
pkgadd, this function will always return an empty string for a given
package.
'''
kwargs.pop('refresh', True)
ret = {}
if not names:
return ''
for name in names:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def install(name=None, sources=None, saltenv='base', **kwargs):
'''
Install the passed package. Can install packages from the following
sources:
* Locally (package already exists on the minion
* HTTP/HTTPS server
* FTP server
* Salt master
Returns a dict containing the new package names and versions:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Examples:
.. code-block:: bash
# Installing a data stream pkg that already exists on the minion
salt '*' pkg.install sources='[{"<pkg name>": "/dir/on/minion/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]'
# Installing a data stream pkg that exists on the salt master
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "salt://pkgs/gcc-3.4.6-sol10-sparc-local.pkg"}]'
CLI Example:
.. code-block:: bash
# Installing a data stream pkg that exists on a HTTP server
salt '*' pkg.install sources='[{"<pkg name>": "http://packages.server.com/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "http://packages.server.com/gcc-3.4.6-sol10-sparc-local.pkg"}]'
If working with solaris zones and you want to install a package only in the
global zone you can pass 'current_zone_only=True' to salt to have the
package only installed in the global zone. (Behind the scenes this is
passing '-G' to the pkgadd command.) Solaris default when installing a
package in the global zone is to install it in all zones. This overrides
that and installs the package only in the global.
CLI Example:
.. code-block:: bash
# Installing a data stream package only in the global zone:
salt 'global_zone' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]' current_zone_only=True
By default salt automatically provides an adminfile, to automate package
installation, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
CLI Example:
.. code-block:: bash
# Overriding the 'instance' adminfile option when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' instance="overwrite"
SLS Example:
.. code-block:: yaml
# Overriding the 'instance' adminfile option when used in a state
SMClgcc346:
pkg.installed:
- sources:
- SMClgcc346: salt://srv/salt/pkgs/gcc-3.4.6-sol10-sparc-local.pkg
- instance: overwrite
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
CLI Example:
.. code-block:: bash
# Providing your own adminfile when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' admin_source='salt://pkgs/<adminfile filename>'
# Providing your own adminfile when using states
<pkg name>:
pkg.installed:
- sources:
- <pkg name>: salt://pkgs/<pkg filename>
- admin_source: salt://pkgs/<adminfile filename>
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
'''
if salt.utils.data.is_true(kwargs.get('refresh')):
log.warning('\'refresh\' argument not implemented for solarispkg '
'module')
# pkgs is not supported, but must be passed here for API compatibility
pkgs = kwargs.pop('pkgs', None)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if not sources:
log.error('"sources" param required for solaris pkg_add installs')
return {}
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
adminfile = _write_adminfile(kwargs)
old = list_pkgs()
cmd_prefix = ['/usr/sbin/pkgadd', '-n', '-a', adminfile]
# Only makes sense in a global zone but works fine in non-globals.
if kwargs.get('current_zone_only') == 'True':
cmd_prefix += '-G '
errors = []
for pkg in pkg_params:
cmd = cmd_prefix + ['-d', pkg, 'all']
# Install the package{s}
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret
def remove(name=None, pkgs=None, saltenv='base', **kwargs):
'''
Remove packages with pkgrm
name
The name of the package to be deleted
By default salt automatically provides an adminfile, to automate package
removal, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove SUNWgit
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
# Make tempfile to hold the adminfile contents.
adminfile = _write_adminfile(kwargs)
# Remove the package
cmd = ['/usr/sbin/pkgrm', '-n', '-a', adminfile] + targets
out = __salt__['cmd.run_all'](cmd,
python_shell=False,
output_loglevel='trace')
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
name
The name of the package to be deleted
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs, **kwargs)
|
saltstack/salt
|
salt/modules/solarispkg.py
|
list_pkgs
|
python
|
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict:
.. code-block:: python
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {}
cmd = '/usr/bin/pkginfo -x'
# Package information returned two lines per package. On even-offset
# lines, the package name is in the first column. On odd-offset lines, the
# package version is in the second column.
lines = __salt__['cmd.run'](
cmd,
output_loglevel='trace',
python_shell=False).splitlines()
for index, line in enumerate(lines):
if index % 2 == 0:
name = line.split()[0].strip()
if index % 2 == 1:
version_num = line.split()[1].strip()
__salt__['pkg_resource.add_pkg'](ret, name, version_num)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
|
List the packages currently installed as a dict:
.. code-block:: python
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solarispkg.py#L82-L131
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for Solaris
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import logging
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, MinionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Solaris
'''
if __grains__['os_family'] == 'Solaris' and float(__grains__['kernelrelease']) <= 5.10:
return __virtualname__
return (False,
'The solarispkg execution module failed to load: only available '
'on Solaris <= 10.')
def _write_adminfile(kwargs):
'''
Create a temporary adminfile based on the keyword arguments passed to
pkg.install.
'''
# Set the adminfile default variables
email = kwargs.get('email', '')
instance = kwargs.get('instance', 'quit')
partial = kwargs.get('partial', 'nocheck')
runlevel = kwargs.get('runlevel', 'nocheck')
idepend = kwargs.get('idepend', 'nocheck')
rdepend = kwargs.get('rdepend', 'nocheck')
space = kwargs.get('space', 'nocheck')
setuid = kwargs.get('setuid', 'nocheck')
conflict = kwargs.get('conflict', 'nocheck')
action = kwargs.get('action', 'nocheck')
basedir = kwargs.get('basedir', 'default')
# Make tempfile to hold the adminfile contents.
adminfile = salt.utils.files.mkstemp(prefix="salt-")
def _write_line(fp_, line):
fp_.write(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(adminfile, 'w') as fp_:
_write_line(fp_, 'email={0}\n'.format(email))
_write_line(fp_, 'instance={0}\n'.format(instance))
_write_line(fp_, 'partial={0}\n'.format(partial))
_write_line(fp_, 'runlevel={0}\n'.format(runlevel))
_write_line(fp_, 'idepend={0}\n'.format(idepend))
_write_line(fp_, 'rdepend={0}\n'.format(rdepend))
_write_line(fp_, 'space={0}\n'.format(space))
_write_line(fp_, 'setuid={0}\n'.format(setuid))
_write_line(fp_, 'conflict={0}\n'.format(conflict))
_write_line(fp_, 'action={0}\n'.format(action))
_write_line(fp_, 'basedir={0}\n'.format(basedir))
return adminfile
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
NOTE: As package repositories are not presently supported for Solaris
pkgadd, this function will always return an empty string for a given
package.
'''
kwargs.pop('refresh', True)
ret = {}
if not names:
return ''
for name in names:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def install(name=None, sources=None, saltenv='base', **kwargs):
'''
Install the passed package. Can install packages from the following
sources:
* Locally (package already exists on the minion
* HTTP/HTTPS server
* FTP server
* Salt master
Returns a dict containing the new package names and versions:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Examples:
.. code-block:: bash
# Installing a data stream pkg that already exists on the minion
salt '*' pkg.install sources='[{"<pkg name>": "/dir/on/minion/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]'
# Installing a data stream pkg that exists on the salt master
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "salt://pkgs/gcc-3.4.6-sol10-sparc-local.pkg"}]'
CLI Example:
.. code-block:: bash
# Installing a data stream pkg that exists on a HTTP server
salt '*' pkg.install sources='[{"<pkg name>": "http://packages.server.com/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "http://packages.server.com/gcc-3.4.6-sol10-sparc-local.pkg"}]'
If working with solaris zones and you want to install a package only in the
global zone you can pass 'current_zone_only=True' to salt to have the
package only installed in the global zone. (Behind the scenes this is
passing '-G' to the pkgadd command.) Solaris default when installing a
package in the global zone is to install it in all zones. This overrides
that and installs the package only in the global.
CLI Example:
.. code-block:: bash
# Installing a data stream package only in the global zone:
salt 'global_zone' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]' current_zone_only=True
By default salt automatically provides an adminfile, to automate package
installation, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
CLI Example:
.. code-block:: bash
# Overriding the 'instance' adminfile option when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' instance="overwrite"
SLS Example:
.. code-block:: yaml
# Overriding the 'instance' adminfile option when used in a state
SMClgcc346:
pkg.installed:
- sources:
- SMClgcc346: salt://srv/salt/pkgs/gcc-3.4.6-sol10-sparc-local.pkg
- instance: overwrite
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
CLI Example:
.. code-block:: bash
# Providing your own adminfile when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' admin_source='salt://pkgs/<adminfile filename>'
# Providing your own adminfile when using states
<pkg name>:
pkg.installed:
- sources:
- <pkg name>: salt://pkgs/<pkg filename>
- admin_source: salt://pkgs/<adminfile filename>
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
'''
if salt.utils.data.is_true(kwargs.get('refresh')):
log.warning('\'refresh\' argument not implemented for solarispkg '
'module')
# pkgs is not supported, but must be passed here for API compatibility
pkgs = kwargs.pop('pkgs', None)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if not sources:
log.error('"sources" param required for solaris pkg_add installs')
return {}
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
adminfile = _write_adminfile(kwargs)
old = list_pkgs()
cmd_prefix = ['/usr/sbin/pkgadd', '-n', '-a', adminfile]
# Only makes sense in a global zone but works fine in non-globals.
if kwargs.get('current_zone_only') == 'True':
cmd_prefix += '-G '
errors = []
for pkg in pkg_params:
cmd = cmd_prefix + ['-d', pkg, 'all']
# Install the package{s}
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret
def remove(name=None, pkgs=None, saltenv='base', **kwargs):
'''
Remove packages with pkgrm
name
The name of the package to be deleted
By default salt automatically provides an adminfile, to automate package
removal, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove SUNWgit
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
# Make tempfile to hold the adminfile contents.
adminfile = _write_adminfile(kwargs)
# Remove the package
cmd = ['/usr/sbin/pkgrm', '-n', '-a', adminfile] + targets
out = __salt__['cmd.run_all'](cmd,
python_shell=False,
output_loglevel='trace')
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
name
The name of the package to be deleted
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs, **kwargs)
|
saltstack/salt
|
salt/modules/solarispkg.py
|
install
|
python
|
def install(name=None, sources=None, saltenv='base', **kwargs):
'''
Install the passed package. Can install packages from the following
sources:
* Locally (package already exists on the minion
* HTTP/HTTPS server
* FTP server
* Salt master
Returns a dict containing the new package names and versions:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Examples:
.. code-block:: bash
# Installing a data stream pkg that already exists on the minion
salt '*' pkg.install sources='[{"<pkg name>": "/dir/on/minion/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]'
# Installing a data stream pkg that exists on the salt master
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "salt://pkgs/gcc-3.4.6-sol10-sparc-local.pkg"}]'
CLI Example:
.. code-block:: bash
# Installing a data stream pkg that exists on a HTTP server
salt '*' pkg.install sources='[{"<pkg name>": "http://packages.server.com/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "http://packages.server.com/gcc-3.4.6-sol10-sparc-local.pkg"}]'
If working with solaris zones and you want to install a package only in the
global zone you can pass 'current_zone_only=True' to salt to have the
package only installed in the global zone. (Behind the scenes this is
passing '-G' to the pkgadd command.) Solaris default when installing a
package in the global zone is to install it in all zones. This overrides
that and installs the package only in the global.
CLI Example:
.. code-block:: bash
# Installing a data stream package only in the global zone:
salt 'global_zone' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]' current_zone_only=True
By default salt automatically provides an adminfile, to automate package
installation, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
CLI Example:
.. code-block:: bash
# Overriding the 'instance' adminfile option when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' instance="overwrite"
SLS Example:
.. code-block:: yaml
# Overriding the 'instance' adminfile option when used in a state
SMClgcc346:
pkg.installed:
- sources:
- SMClgcc346: salt://srv/salt/pkgs/gcc-3.4.6-sol10-sparc-local.pkg
- instance: overwrite
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
CLI Example:
.. code-block:: bash
# Providing your own adminfile when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' admin_source='salt://pkgs/<adminfile filename>'
# Providing your own adminfile when using states
<pkg name>:
pkg.installed:
- sources:
- <pkg name>: salt://pkgs/<pkg filename>
- admin_source: salt://pkgs/<adminfile filename>
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
'''
if salt.utils.data.is_true(kwargs.get('refresh')):
log.warning('\'refresh\' argument not implemented for solarispkg '
'module')
# pkgs is not supported, but must be passed here for API compatibility
pkgs = kwargs.pop('pkgs', None)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if not sources:
log.error('"sources" param required for solaris pkg_add installs')
return {}
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
adminfile = _write_adminfile(kwargs)
old = list_pkgs()
cmd_prefix = ['/usr/sbin/pkgadd', '-n', '-a', adminfile]
# Only makes sense in a global zone but works fine in non-globals.
if kwargs.get('current_zone_only') == 'True':
cmd_prefix += '-G '
errors = []
for pkg in pkg_params:
cmd = cmd_prefix + ['-d', pkg, 'all']
# Install the package{s}
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret
|
Install the passed package. Can install packages from the following
sources:
* Locally (package already exists on the minion
* HTTP/HTTPS server
* FTP server
* Salt master
Returns a dict containing the new package names and versions:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Examples:
.. code-block:: bash
# Installing a data stream pkg that already exists on the minion
salt '*' pkg.install sources='[{"<pkg name>": "/dir/on/minion/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]'
# Installing a data stream pkg that exists on the salt master
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "salt://pkgs/gcc-3.4.6-sol10-sparc-local.pkg"}]'
CLI Example:
.. code-block:: bash
# Installing a data stream pkg that exists on a HTTP server
salt '*' pkg.install sources='[{"<pkg name>": "http://packages.server.com/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "http://packages.server.com/gcc-3.4.6-sol10-sparc-local.pkg"}]'
If working with solaris zones and you want to install a package only in the
global zone you can pass 'current_zone_only=True' to salt to have the
package only installed in the global zone. (Behind the scenes this is
passing '-G' to the pkgadd command.) Solaris default when installing a
package in the global zone is to install it in all zones. This overrides
that and installs the package only in the global.
CLI Example:
.. code-block:: bash
# Installing a data stream package only in the global zone:
salt 'global_zone' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]' current_zone_only=True
By default salt automatically provides an adminfile, to automate package
installation, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
CLI Example:
.. code-block:: bash
# Overriding the 'instance' adminfile option when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' instance="overwrite"
SLS Example:
.. code-block:: yaml
# Overriding the 'instance' adminfile option when used in a state
SMClgcc346:
pkg.installed:
- sources:
- SMClgcc346: salt://srv/salt/pkgs/gcc-3.4.6-sol10-sparc-local.pkg
- instance: overwrite
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
CLI Example:
.. code-block:: bash
# Providing your own adminfile when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' admin_source='salt://pkgs/<adminfile filename>'
# Providing your own adminfile when using states
<pkg name>:
pkg.installed:
- sources:
- <pkg name>: salt://pkgs/<pkg filename>
- admin_source: salt://pkgs/<adminfile filename>
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solarispkg.py#L201-L385
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed as a dict:\n\n .. code-block:: python\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n if versions_as_list:\n return __context__['pkg.list_pkgs']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n ret = {}\n cmd = '/usr/bin/pkginfo -x'\n\n # Package information returned two lines per package. On even-offset\n # lines, the package name is in the first column. On odd-offset lines, the\n # package version is in the second column.\n lines = __salt__['cmd.run'](\n cmd,\n output_loglevel='trace',\n python_shell=False).splitlines()\n for index, line in enumerate(lines):\n if index % 2 == 0:\n name = line.split()[0].strip()\n if index % 2 == 1:\n version_num = line.split()[1].strip()\n __salt__['pkg_resource.add_pkg'](ret, name, version_num)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def _write_adminfile(kwargs):\n '''\n Create a temporary adminfile based on the keyword arguments passed to\n pkg.install.\n '''\n # Set the adminfile default variables\n email = kwargs.get('email', '')\n instance = kwargs.get('instance', 'quit')\n partial = kwargs.get('partial', 'nocheck')\n runlevel = kwargs.get('runlevel', 'nocheck')\n idepend = kwargs.get('idepend', 'nocheck')\n rdepend = kwargs.get('rdepend', 'nocheck')\n space = kwargs.get('space', 'nocheck')\n setuid = kwargs.get('setuid', 'nocheck')\n conflict = kwargs.get('conflict', 'nocheck')\n action = kwargs.get('action', 'nocheck')\n basedir = kwargs.get('basedir', 'default')\n\n # Make tempfile to hold the adminfile contents.\n adminfile = salt.utils.files.mkstemp(prefix=\"salt-\")\n\n def _write_line(fp_, line):\n fp_.write(salt.utils.stringutils.to_str(line))\n\n with salt.utils.files.fopen(adminfile, 'w') as fp_:\n _write_line(fp_, 'email={0}\\n'.format(email))\n _write_line(fp_, 'instance={0}\\n'.format(instance))\n _write_line(fp_, 'partial={0}\\n'.format(partial))\n _write_line(fp_, 'runlevel={0}\\n'.format(runlevel))\n _write_line(fp_, 'idepend={0}\\n'.format(idepend))\n _write_line(fp_, 'rdepend={0}\\n'.format(rdepend))\n _write_line(fp_, 'space={0}\\n'.format(space))\n _write_line(fp_, 'setuid={0}\\n'.format(setuid))\n _write_line(fp_, 'conflict={0}\\n'.format(conflict))\n _write_line(fp_, 'action={0}\\n'.format(action))\n _write_line(fp_, 'basedir={0}\\n'.format(basedir))\n\n return adminfile\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for Solaris
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import logging
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, MinionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Solaris
'''
if __grains__['os_family'] == 'Solaris' and float(__grains__['kernelrelease']) <= 5.10:
return __virtualname__
return (False,
'The solarispkg execution module failed to load: only available '
'on Solaris <= 10.')
def _write_adminfile(kwargs):
'''
Create a temporary adminfile based on the keyword arguments passed to
pkg.install.
'''
# Set the adminfile default variables
email = kwargs.get('email', '')
instance = kwargs.get('instance', 'quit')
partial = kwargs.get('partial', 'nocheck')
runlevel = kwargs.get('runlevel', 'nocheck')
idepend = kwargs.get('idepend', 'nocheck')
rdepend = kwargs.get('rdepend', 'nocheck')
space = kwargs.get('space', 'nocheck')
setuid = kwargs.get('setuid', 'nocheck')
conflict = kwargs.get('conflict', 'nocheck')
action = kwargs.get('action', 'nocheck')
basedir = kwargs.get('basedir', 'default')
# Make tempfile to hold the adminfile contents.
adminfile = salt.utils.files.mkstemp(prefix="salt-")
def _write_line(fp_, line):
fp_.write(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(adminfile, 'w') as fp_:
_write_line(fp_, 'email={0}\n'.format(email))
_write_line(fp_, 'instance={0}\n'.format(instance))
_write_line(fp_, 'partial={0}\n'.format(partial))
_write_line(fp_, 'runlevel={0}\n'.format(runlevel))
_write_line(fp_, 'idepend={0}\n'.format(idepend))
_write_line(fp_, 'rdepend={0}\n'.format(rdepend))
_write_line(fp_, 'space={0}\n'.format(space))
_write_line(fp_, 'setuid={0}\n'.format(setuid))
_write_line(fp_, 'conflict={0}\n'.format(conflict))
_write_line(fp_, 'action={0}\n'.format(action))
_write_line(fp_, 'basedir={0}\n'.format(basedir))
return adminfile
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict:
.. code-block:: python
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {}
cmd = '/usr/bin/pkginfo -x'
# Package information returned two lines per package. On even-offset
# lines, the package name is in the first column. On odd-offset lines, the
# package version is in the second column.
lines = __salt__['cmd.run'](
cmd,
output_loglevel='trace',
python_shell=False).splitlines()
for index, line in enumerate(lines):
if index % 2 == 0:
name = line.split()[0].strip()
if index % 2 == 1:
version_num = line.split()[1].strip()
__salt__['pkg_resource.add_pkg'](ret, name, version_num)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
NOTE: As package repositories are not presently supported for Solaris
pkgadd, this function will always return an empty string for a given
package.
'''
kwargs.pop('refresh', True)
ret = {}
if not names:
return ''
for name in names:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def remove(name=None, pkgs=None, saltenv='base', **kwargs):
'''
Remove packages with pkgrm
name
The name of the package to be deleted
By default salt automatically provides an adminfile, to automate package
removal, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove SUNWgit
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
# Make tempfile to hold the adminfile contents.
adminfile = _write_adminfile(kwargs)
# Remove the package
cmd = ['/usr/sbin/pkgrm', '-n', '-a', adminfile] + targets
out = __salt__['cmd.run_all'](cmd,
python_shell=False,
output_loglevel='trace')
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
name
The name of the package to be deleted
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs, **kwargs)
|
saltstack/salt
|
salt/modules/solarispkg.py
|
remove
|
python
|
def remove(name=None, pkgs=None, saltenv='base', **kwargs):
'''
Remove packages with pkgrm
name
The name of the package to be deleted
By default salt automatically provides an adminfile, to automate package
removal, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove SUNWgit
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
# Make tempfile to hold the adminfile contents.
adminfile = _write_adminfile(kwargs)
# Remove the package
cmd = ['/usr/sbin/pkgrm', '-n', '-a', adminfile] + targets
out = __salt__['cmd.run_all'](cmd,
python_shell=False,
output_loglevel='trace')
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret
|
Remove packages with pkgrm
name
The name of the package to be deleted
By default salt automatically provides an adminfile, to automate package
removal, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove SUNWgit
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solarispkg.py#L388-L488
|
[
"def list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed as a dict:\n\n .. code-block:: python\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n if versions_as_list:\n return __context__['pkg.list_pkgs']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n ret = {}\n cmd = '/usr/bin/pkginfo -x'\n\n # Package information returned two lines per package. On even-offset\n # lines, the package name is in the first column. On odd-offset lines, the\n # package version is in the second column.\n lines = __salt__['cmd.run'](\n cmd,\n output_loglevel='trace',\n python_shell=False).splitlines()\n for index, line in enumerate(lines):\n if index % 2 == 0:\n name = line.split()[0].strip()\n if index % 2 == 1:\n version_num = line.split()[1].strip()\n __salt__['pkg_resource.add_pkg'](ret, name, version_num)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def _write_adminfile(kwargs):\n '''\n Create a temporary adminfile based on the keyword arguments passed to\n pkg.install.\n '''\n # Set the adminfile default variables\n email = kwargs.get('email', '')\n instance = kwargs.get('instance', 'quit')\n partial = kwargs.get('partial', 'nocheck')\n runlevel = kwargs.get('runlevel', 'nocheck')\n idepend = kwargs.get('idepend', 'nocheck')\n rdepend = kwargs.get('rdepend', 'nocheck')\n space = kwargs.get('space', 'nocheck')\n setuid = kwargs.get('setuid', 'nocheck')\n conflict = kwargs.get('conflict', 'nocheck')\n action = kwargs.get('action', 'nocheck')\n basedir = kwargs.get('basedir', 'default')\n\n # Make tempfile to hold the adminfile contents.\n adminfile = salt.utils.files.mkstemp(prefix=\"salt-\")\n\n def _write_line(fp_, line):\n fp_.write(salt.utils.stringutils.to_str(line))\n\n with salt.utils.files.fopen(adminfile, 'w') as fp_:\n _write_line(fp_, 'email={0}\\n'.format(email))\n _write_line(fp_, 'instance={0}\\n'.format(instance))\n _write_line(fp_, 'partial={0}\\n'.format(partial))\n _write_line(fp_, 'runlevel={0}\\n'.format(runlevel))\n _write_line(fp_, 'idepend={0}\\n'.format(idepend))\n _write_line(fp_, 'rdepend={0}\\n'.format(rdepend))\n _write_line(fp_, 'space={0}\\n'.format(space))\n _write_line(fp_, 'setuid={0}\\n'.format(setuid))\n _write_line(fp_, 'conflict={0}\\n'.format(conflict))\n _write_line(fp_, 'action={0}\\n'.format(action))\n _write_line(fp_, 'basedir={0}\\n'.format(basedir))\n\n return adminfile\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for Solaris
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import logging
# Import salt libs
import salt.utils.data
import salt.utils.functools
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, MinionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Solaris
'''
if __grains__['os_family'] == 'Solaris' and float(__grains__['kernelrelease']) <= 5.10:
return __virtualname__
return (False,
'The solarispkg execution module failed to load: only available '
'on Solaris <= 10.')
def _write_adminfile(kwargs):
'''
Create a temporary adminfile based on the keyword arguments passed to
pkg.install.
'''
# Set the adminfile default variables
email = kwargs.get('email', '')
instance = kwargs.get('instance', 'quit')
partial = kwargs.get('partial', 'nocheck')
runlevel = kwargs.get('runlevel', 'nocheck')
idepend = kwargs.get('idepend', 'nocheck')
rdepend = kwargs.get('rdepend', 'nocheck')
space = kwargs.get('space', 'nocheck')
setuid = kwargs.get('setuid', 'nocheck')
conflict = kwargs.get('conflict', 'nocheck')
action = kwargs.get('action', 'nocheck')
basedir = kwargs.get('basedir', 'default')
# Make tempfile to hold the adminfile contents.
adminfile = salt.utils.files.mkstemp(prefix="salt-")
def _write_line(fp_, line):
fp_.write(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(adminfile, 'w') as fp_:
_write_line(fp_, 'email={0}\n'.format(email))
_write_line(fp_, 'instance={0}\n'.format(instance))
_write_line(fp_, 'partial={0}\n'.format(partial))
_write_line(fp_, 'runlevel={0}\n'.format(runlevel))
_write_line(fp_, 'idepend={0}\n'.format(idepend))
_write_line(fp_, 'rdepend={0}\n'.format(rdepend))
_write_line(fp_, 'space={0}\n'.format(space))
_write_line(fp_, 'setuid={0}\n'.format(setuid))
_write_line(fp_, 'conflict={0}\n'.format(conflict))
_write_line(fp_, 'action={0}\n'.format(action))
_write_line(fp_, 'basedir={0}\n'.format(basedir))
return adminfile
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict:
.. code-block:: python
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {}
cmd = '/usr/bin/pkginfo -x'
# Package information returned two lines per package. On even-offset
# lines, the package name is in the first column. On odd-offset lines, the
# package version is in the second column.
lines = __salt__['cmd.run'](
cmd,
output_loglevel='trace',
python_shell=False).splitlines()
for index, line in enumerate(lines):
if index % 2 == 0:
name = line.split()[0].strip()
if index % 2 == 1:
version_num = line.split()[1].strip()
__salt__['pkg_resource.add_pkg'](ret, name, version_num)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
NOTE: As package repositories are not presently supported for Solaris
pkgadd, this function will always return an empty string for a given
package.
'''
kwargs.pop('refresh', True)
ret = {}
if not names:
return ''
for name in names:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def install(name=None, sources=None, saltenv='base', **kwargs):
'''
Install the passed package. Can install packages from the following
sources:
* Locally (package already exists on the minion
* HTTP/HTTPS server
* FTP server
* Salt master
Returns a dict containing the new package names and versions:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Examples:
.. code-block:: bash
# Installing a data stream pkg that already exists on the minion
salt '*' pkg.install sources='[{"<pkg name>": "/dir/on/minion/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]'
# Installing a data stream pkg that exists on the salt master
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "salt://pkgs/gcc-3.4.6-sol10-sparc-local.pkg"}]'
CLI Example:
.. code-block:: bash
# Installing a data stream pkg that exists on a HTTP server
salt '*' pkg.install sources='[{"<pkg name>": "http://packages.server.com/<pkg filename>"}]'
salt '*' pkg.install sources='[{"SMClgcc346": "http://packages.server.com/gcc-3.4.6-sol10-sparc-local.pkg"}]'
If working with solaris zones and you want to install a package only in the
global zone you can pass 'current_zone_only=True' to salt to have the
package only installed in the global zone. (Behind the scenes this is
passing '-G' to the pkgadd command.) Solaris default when installing a
package in the global zone is to install it in all zones. This overrides
that and installs the package only in the global.
CLI Example:
.. code-block:: bash
# Installing a data stream package only in the global zone:
salt 'global_zone' pkg.install sources='[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]' current_zone_only=True
By default salt automatically provides an adminfile, to automate package
installation, with these options set::
email=
instance=quit
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
You can override any of these options in two ways. First you can optionally
pass any of the options as a kwarg to the module/state to override the
default value or you can optionally pass the 'admin_source' option
providing your own adminfile to the minions.
Note: You can find all of the possible options to provide to the adminfile
by reading the admin man page:
.. code-block:: bash
man -s 4 admin
CLI Example:
.. code-block:: bash
# Overriding the 'instance' adminfile option when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' instance="overwrite"
SLS Example:
.. code-block:: yaml
# Overriding the 'instance' adminfile option when used in a state
SMClgcc346:
pkg.installed:
- sources:
- SMClgcc346: salt://srv/salt/pkgs/gcc-3.4.6-sol10-sparc-local.pkg
- instance: overwrite
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
CLI Example:
.. code-block:: bash
# Providing your own adminfile when calling the module directly
salt '*' pkg.install sources='[{"<pkg name>": "salt://pkgs/<pkg filename>"}]' admin_source='salt://pkgs/<adminfile filename>'
# Providing your own adminfile when using states
<pkg name>:
pkg.installed:
- sources:
- <pkg name>: salt://pkgs/<pkg filename>
- admin_source: salt://pkgs/<adminfile filename>
.. note::
The ID declaration is ignored, as the package name is read from the
``sources`` parameter.
'''
if salt.utils.data.is_true(kwargs.get('refresh')):
log.warning('\'refresh\' argument not implemented for solarispkg '
'module')
# pkgs is not supported, but must be passed here for API compatibility
pkgs = kwargs.pop('pkgs', None)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if not sources:
log.error('"sources" param required for solaris pkg_add installs')
return {}
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
adminfile = _write_adminfile(kwargs)
old = list_pkgs()
cmd_prefix = ['/usr/sbin/pkgadd', '-n', '-a', adminfile]
# Only makes sense in a global zone but works fine in non-globals.
if kwargs.get('current_zone_only') == 'True':
cmd_prefix += '-G '
errors = []
for pkg in pkg_params:
cmd = cmd_prefix + ['-d', pkg, 'all']
# Install the package{s}
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret
def purge(name=None, pkgs=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
name
The name of the package to be deleted
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs, **kwargs)
|
saltstack/salt
|
salt/states/boto_cloudtrail.py
|
present
|
python
|
def present(name, Name,
S3BucketName, S3KeyPrefix=None,
SnsTopicName=None,
IncludeGlobalServiceEvents=True,
IsMultiRegionTrail=None,
EnableLogFileValidation=False,
CloudWatchLogsLogGroupArn=None,
CloudWatchLogsRoleArn=None,
KmsKeyId=None,
LoggingEnabled=True,
Tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure trail exists.
name
The name of the state definition
Name
Name of the trail.
S3BucketName
Specifies the name of the Amazon S3 bucket designated for publishing log
files.
S3KeyPrefix
Specifies the Amazon S3 key prefix that comes after the name of the
bucket you have designated for log file delivery.
SnsTopicName
Specifies the name of the Amazon SNS topic defined for notification of
log file delivery. The maximum length is 256 characters.
IncludeGlobalServiceEvents
Specifies whether the trail is publishing events from global services
such as IAM to the log files.
EnableLogFileValidation
Specifies whether log file integrity validation is enabled. The default
is false.
CloudWatchLogsLogGroupArn
Specifies a log group name using an Amazon Resource Name (ARN), a unique
identifier that represents the log group to which CloudTrail logs will
be delivered. Not required unless you specify CloudWatchLogsRoleArn.
CloudWatchLogsRoleArn
Specifies the role for the CloudWatch Logs endpoint to assume to write
to a user's log group.
KmsKeyId
Specifies the KMS key ID to use to encrypt the logs delivered by
CloudTrail. The value can be a an alias name prefixed by "alias/", a
fully specified ARN to an alias, a fully specified ARN to a key, or a
globally unique identifier.
LoggingEnabled
Whether logging should be enabled for the trail
Tags
A dictionary of tags that should be set on the trail
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': Name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_cloudtrail.exists'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create trail: {0}.'.format(r['error']['message'])
return ret
if not r.get('exists'):
if __opts__['test']:
ret['comment'] = 'CloudTrail {0} is set to be created.'.format(Name)
ret['result'] = None
return ret
r = __salt__['boto_cloudtrail.create'](Name=Name,
S3BucketName=S3BucketName,
S3KeyPrefix=S3KeyPrefix,
SnsTopicName=SnsTopicName,
IncludeGlobalServiceEvents=IncludeGlobalServiceEvents,
IsMultiRegionTrail=IsMultiRegionTrail,
EnableLogFileValidation=EnableLogFileValidation,
CloudWatchLogsLogGroupArn=CloudWatchLogsLogGroupArn,
CloudWatchLogsRoleArn=CloudWatchLogsRoleArn,
KmsKeyId=KmsKeyId,
region=region, key=key, keyid=keyid, profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create trail: {0}.'.format(r['error']['message'])
return ret
_describe = __salt__['boto_cloudtrail.describe'](Name,
region=region, key=key, keyid=keyid, profile=profile)
ret['changes']['old'] = {'trail': None}
ret['changes']['new'] = _describe
ret['comment'] = 'CloudTrail {0} created.'.format(Name)
if LoggingEnabled:
r = __salt__['boto_cloudtrail.start_logging'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
ret['changes']['new']['trail']['LoggingEnabled'] = True
else:
ret['changes']['new']['trail']['LoggingEnabled'] = False
if bool(Tags):
r = __salt__['boto_cloudtrail.add_tags'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile, **Tags)
if not r.get('tagged'):
ret['result'] = False
ret['comment'] = 'Failed to create trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
ret['changes']['new']['trail']['Tags'] = Tags
return ret
ret['comment'] = os.linesep.join([ret['comment'], 'CloudTrail {0} is present.'.format(Name)])
ret['changes'] = {}
# trail exists, ensure config matches
_describe = __salt__['boto_cloudtrail.describe'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in _describe:
ret['result'] = False
ret['comment'] = 'Failed to update trail: {0}.'.format(_describe['error']['message'])
ret['changes'] = {}
return ret
_describe = _describe.get('trail')
r = __salt__['boto_cloudtrail.status'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
_describe['LoggingEnabled'] = r.get('trail', {}).get('IsLogging', False)
need_update = False
bucket_vars = {'S3BucketName': 'S3BucketName',
'S3KeyPrefix': 'S3KeyPrefix',
'SnsTopicName': 'SnsTopicName',
'IncludeGlobalServiceEvents': 'IncludeGlobalServiceEvents',
'IsMultiRegionTrail': 'IsMultiRegionTrail',
'EnableLogFileValidation': 'LogFileValidationEnabled',
'CloudWatchLogsLogGroupArn': 'CloudWatchLogsLogGroupArn',
'CloudWatchLogsRoleArn': 'CloudWatchLogsRoleArn',
'KmsKeyId': 'KmsKeyId',
'LoggingEnabled': 'LoggingEnabled'}
for invar, outvar in six.iteritems(bucket_vars):
if _describe[outvar] != locals()[invar]:
need_update = True
ret['changes'].setdefault('new', {})[invar] = locals()[invar]
ret['changes'].setdefault('old', {})[invar] = _describe[outvar]
r = __salt__['boto_cloudtrail.list_tags'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
_describe['Tags'] = r.get('tags', {})
tagchange = salt.utils.data.compare_dicts(_describe['Tags'], Tags)
if bool(tagchange):
need_update = True
ret['changes'].setdefault('new', {})['Tags'] = Tags
ret['changes'].setdefault('old', {})['Tags'] = _describe['Tags']
if need_update:
if __opts__['test']:
msg = 'CloudTrail {0} set to be modified.'.format(Name)
ret['comment'] = msg
ret['result'] = None
return ret
ret['comment'] = os.linesep.join([ret['comment'], 'CloudTrail to be modified'])
r = __salt__['boto_cloudtrail.update'](Name=Name,
S3BucketName=S3BucketName,
S3KeyPrefix=S3KeyPrefix,
SnsTopicName=SnsTopicName,
IncludeGlobalServiceEvents=IncludeGlobalServiceEvents,
IsMultiRegionTrail=IsMultiRegionTrail,
EnableLogFileValidation=EnableLogFileValidation,
CloudWatchLogsLogGroupArn=CloudWatchLogsLogGroupArn,
CloudWatchLogsRoleArn=CloudWatchLogsRoleArn,
KmsKeyId=KmsKeyId,
region=region, key=key, keyid=keyid, profile=profile)
if not r.get('updated'):
ret['result'] = False
ret['comment'] = 'Failed to update trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
if LoggingEnabled:
r = __salt__['boto_cloudtrail.start_logging'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if not r.get('started'):
ret['result'] = False
ret['comment'] = 'Failed to update trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
else:
r = __salt__['boto_cloudtrail.stop_logging'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if not r.get('stopped'):
ret['result'] = False
ret['comment'] = 'Failed to update trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
if bool(tagchange):
adds = {}
removes = {}
for k, diff in six.iteritems(tagchange):
if diff.get('new', '') != '':
# there's an update for this key
adds[k] = Tags[k]
elif diff.get('old', '') != '':
removes[k] = _describe['Tags'][k]
if bool(adds):
r = __salt__['boto_cloudtrail.add_tags'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile, **adds)
if bool(removes):
r = __salt__['boto_cloudtrail.remove_tags'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile,
**removes)
return ret
|
Ensure trail exists.
name
The name of the state definition
Name
Name of the trail.
S3BucketName
Specifies the name of the Amazon S3 bucket designated for publishing log
files.
S3KeyPrefix
Specifies the Amazon S3 key prefix that comes after the name of the
bucket you have designated for log file delivery.
SnsTopicName
Specifies the name of the Amazon SNS topic defined for notification of
log file delivery. The maximum length is 256 characters.
IncludeGlobalServiceEvents
Specifies whether the trail is publishing events from global services
such as IAM to the log files.
EnableLogFileValidation
Specifies whether log file integrity validation is enabled. The default
is false.
CloudWatchLogsLogGroupArn
Specifies a log group name using an Amazon Resource Name (ARN), a unique
identifier that represents the log group to which CloudTrail logs will
be delivered. Not required unless you specify CloudWatchLogsRoleArn.
CloudWatchLogsRoleArn
Specifies the role for the CloudWatch Logs endpoint to assume to write
to a user's log group.
KmsKeyId
Specifies the KMS key ID to use to encrypt the logs delivered by
CloudTrail. The value can be a an alias name prefixed by "alias/", a
fully specified ARN to an alias, a fully specified ARN to a key, or a
globally unique identifier.
LoggingEnabled
Whether logging should be enabled for the trail
Tags
A dictionary of tags that should be set on the trail
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudtrail.py#L75-L315
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage CloudTrail Objects
=========================
.. versionadded:: 2016.3.0
Create and destroy CloudTrail objects. Be aware that this interacts with Amazon's services,
and so may incur charges.
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
This module accepts explicit vpc credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
vpc.keyid: GKTADJGHEIQSXMKKRBJ08H
vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile,
either passed in as a dict, or as a string to pull from pillars or minion
config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure trail exists:
boto_cloudtrail.present:
- Name: mytrail
- S3BucketName: mybucket
- S3KeyPrefix: prefix
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import os.path
# Import Salt Libs
from salt.ext import six
import salt.utils.data
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_cloudtrail' if 'boto_cloudtrail.exists' in __salt__ else False
def absent(name, Name,
region=None, key=None, keyid=None, profile=None):
'''
Ensure trail with passed properties is absent.
name
The name of the state definition.
Name
Name of the trail.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': Name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_cloudtrail.exists'](Name,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete trail: {0}.'.format(r['error']['message'])
return ret
if r and not r['exists']:
ret['comment'] = 'CloudTrail {0} does not exist.'.format(Name)
return ret
if __opts__['test']:
ret['comment'] = 'CloudTrail {0} is set to be removed.'.format(Name)
ret['result'] = None
return ret
r = __salt__['boto_cloudtrail.delete'](Name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r['deleted']:
ret['result'] = False
ret['comment'] = 'Failed to delete trail: {0}.'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'trail': Name}
ret['changes']['new'] = {'trail': None}
ret['comment'] = 'CloudTrail {0} deleted.'.format(Name)
return ret
|
saltstack/salt
|
salt/states/boto_cloudtrail.py
|
absent
|
python
|
def absent(name, Name,
region=None, key=None, keyid=None, profile=None):
'''
Ensure trail with passed properties is absent.
name
The name of the state definition.
Name
Name of the trail.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': Name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_cloudtrail.exists'](Name,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete trail: {0}.'.format(r['error']['message'])
return ret
if r and not r['exists']:
ret['comment'] = 'CloudTrail {0} does not exist.'.format(Name)
return ret
if __opts__['test']:
ret['comment'] = 'CloudTrail {0} is set to be removed.'.format(Name)
ret['result'] = None
return ret
r = __salt__['boto_cloudtrail.delete'](Name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r['deleted']:
ret['result'] = False
ret['comment'] = 'Failed to delete trail: {0}.'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'trail': Name}
ret['changes']['new'] = {'trail': None}
ret['comment'] = 'CloudTrail {0} deleted.'.format(Name)
return ret
|
Ensure trail with passed properties is absent.
name
The name of the state definition.
Name
Name of the trail.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudtrail.py#L318-L374
| null |
# -*- coding: utf-8 -*-
'''
Manage CloudTrail Objects
=========================
.. versionadded:: 2016.3.0
Create and destroy CloudTrail objects. Be aware that this interacts with Amazon's services,
and so may incur charges.
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
This module accepts explicit vpc credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
vpc.keyid: GKTADJGHEIQSXMKKRBJ08H
vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile,
either passed in as a dict, or as a string to pull from pillars or minion
config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure trail exists:
boto_cloudtrail.present:
- Name: mytrail
- S3BucketName: mybucket
- S3KeyPrefix: prefix
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import os.path
# Import Salt Libs
from salt.ext import six
import salt.utils.data
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_cloudtrail' if 'boto_cloudtrail.exists' in __salt__ else False
def present(name, Name,
S3BucketName, S3KeyPrefix=None,
SnsTopicName=None,
IncludeGlobalServiceEvents=True,
IsMultiRegionTrail=None,
EnableLogFileValidation=False,
CloudWatchLogsLogGroupArn=None,
CloudWatchLogsRoleArn=None,
KmsKeyId=None,
LoggingEnabled=True,
Tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure trail exists.
name
The name of the state definition
Name
Name of the trail.
S3BucketName
Specifies the name of the Amazon S3 bucket designated for publishing log
files.
S3KeyPrefix
Specifies the Amazon S3 key prefix that comes after the name of the
bucket you have designated for log file delivery.
SnsTopicName
Specifies the name of the Amazon SNS topic defined for notification of
log file delivery. The maximum length is 256 characters.
IncludeGlobalServiceEvents
Specifies whether the trail is publishing events from global services
such as IAM to the log files.
EnableLogFileValidation
Specifies whether log file integrity validation is enabled. The default
is false.
CloudWatchLogsLogGroupArn
Specifies a log group name using an Amazon Resource Name (ARN), a unique
identifier that represents the log group to which CloudTrail logs will
be delivered. Not required unless you specify CloudWatchLogsRoleArn.
CloudWatchLogsRoleArn
Specifies the role for the CloudWatch Logs endpoint to assume to write
to a user's log group.
KmsKeyId
Specifies the KMS key ID to use to encrypt the logs delivered by
CloudTrail. The value can be a an alias name prefixed by "alias/", a
fully specified ARN to an alias, a fully specified ARN to a key, or a
globally unique identifier.
LoggingEnabled
Whether logging should be enabled for the trail
Tags
A dictionary of tags that should be set on the trail
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': Name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_cloudtrail.exists'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create trail: {0}.'.format(r['error']['message'])
return ret
if not r.get('exists'):
if __opts__['test']:
ret['comment'] = 'CloudTrail {0} is set to be created.'.format(Name)
ret['result'] = None
return ret
r = __salt__['boto_cloudtrail.create'](Name=Name,
S3BucketName=S3BucketName,
S3KeyPrefix=S3KeyPrefix,
SnsTopicName=SnsTopicName,
IncludeGlobalServiceEvents=IncludeGlobalServiceEvents,
IsMultiRegionTrail=IsMultiRegionTrail,
EnableLogFileValidation=EnableLogFileValidation,
CloudWatchLogsLogGroupArn=CloudWatchLogsLogGroupArn,
CloudWatchLogsRoleArn=CloudWatchLogsRoleArn,
KmsKeyId=KmsKeyId,
region=region, key=key, keyid=keyid, profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create trail: {0}.'.format(r['error']['message'])
return ret
_describe = __salt__['boto_cloudtrail.describe'](Name,
region=region, key=key, keyid=keyid, profile=profile)
ret['changes']['old'] = {'trail': None}
ret['changes']['new'] = _describe
ret['comment'] = 'CloudTrail {0} created.'.format(Name)
if LoggingEnabled:
r = __salt__['boto_cloudtrail.start_logging'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
ret['changes']['new']['trail']['LoggingEnabled'] = True
else:
ret['changes']['new']['trail']['LoggingEnabled'] = False
if bool(Tags):
r = __salt__['boto_cloudtrail.add_tags'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile, **Tags)
if not r.get('tagged'):
ret['result'] = False
ret['comment'] = 'Failed to create trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
ret['changes']['new']['trail']['Tags'] = Tags
return ret
ret['comment'] = os.linesep.join([ret['comment'], 'CloudTrail {0} is present.'.format(Name)])
ret['changes'] = {}
# trail exists, ensure config matches
_describe = __salt__['boto_cloudtrail.describe'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in _describe:
ret['result'] = False
ret['comment'] = 'Failed to update trail: {0}.'.format(_describe['error']['message'])
ret['changes'] = {}
return ret
_describe = _describe.get('trail')
r = __salt__['boto_cloudtrail.status'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
_describe['LoggingEnabled'] = r.get('trail', {}).get('IsLogging', False)
need_update = False
bucket_vars = {'S3BucketName': 'S3BucketName',
'S3KeyPrefix': 'S3KeyPrefix',
'SnsTopicName': 'SnsTopicName',
'IncludeGlobalServiceEvents': 'IncludeGlobalServiceEvents',
'IsMultiRegionTrail': 'IsMultiRegionTrail',
'EnableLogFileValidation': 'LogFileValidationEnabled',
'CloudWatchLogsLogGroupArn': 'CloudWatchLogsLogGroupArn',
'CloudWatchLogsRoleArn': 'CloudWatchLogsRoleArn',
'KmsKeyId': 'KmsKeyId',
'LoggingEnabled': 'LoggingEnabled'}
for invar, outvar in six.iteritems(bucket_vars):
if _describe[outvar] != locals()[invar]:
need_update = True
ret['changes'].setdefault('new', {})[invar] = locals()[invar]
ret['changes'].setdefault('old', {})[invar] = _describe[outvar]
r = __salt__['boto_cloudtrail.list_tags'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
_describe['Tags'] = r.get('tags', {})
tagchange = salt.utils.data.compare_dicts(_describe['Tags'], Tags)
if bool(tagchange):
need_update = True
ret['changes'].setdefault('new', {})['Tags'] = Tags
ret['changes'].setdefault('old', {})['Tags'] = _describe['Tags']
if need_update:
if __opts__['test']:
msg = 'CloudTrail {0} set to be modified.'.format(Name)
ret['comment'] = msg
ret['result'] = None
return ret
ret['comment'] = os.linesep.join([ret['comment'], 'CloudTrail to be modified'])
r = __salt__['boto_cloudtrail.update'](Name=Name,
S3BucketName=S3BucketName,
S3KeyPrefix=S3KeyPrefix,
SnsTopicName=SnsTopicName,
IncludeGlobalServiceEvents=IncludeGlobalServiceEvents,
IsMultiRegionTrail=IsMultiRegionTrail,
EnableLogFileValidation=EnableLogFileValidation,
CloudWatchLogsLogGroupArn=CloudWatchLogsLogGroupArn,
CloudWatchLogsRoleArn=CloudWatchLogsRoleArn,
KmsKeyId=KmsKeyId,
region=region, key=key, keyid=keyid, profile=profile)
if not r.get('updated'):
ret['result'] = False
ret['comment'] = 'Failed to update trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
if LoggingEnabled:
r = __salt__['boto_cloudtrail.start_logging'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if not r.get('started'):
ret['result'] = False
ret['comment'] = 'Failed to update trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
else:
r = __salt__['boto_cloudtrail.stop_logging'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile)
if not r.get('stopped'):
ret['result'] = False
ret['comment'] = 'Failed to update trail: {0}.'.format(r['error']['message'])
ret['changes'] = {}
return ret
if bool(tagchange):
adds = {}
removes = {}
for k, diff in six.iteritems(tagchange):
if diff.get('new', '') != '':
# there's an update for this key
adds[k] = Tags[k]
elif diff.get('old', '') != '':
removes[k] = _describe['Tags'][k]
if bool(adds):
r = __salt__['boto_cloudtrail.add_tags'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile, **adds)
if bool(removes):
r = __salt__['boto_cloudtrail.remove_tags'](Name=Name,
region=region, key=key, keyid=keyid, profile=profile,
**removes)
return ret
|
saltstack/salt
|
salt/transport/__init__.py
|
iter_transport_opts
|
python
|
def iter_transport_opts(opts):
'''
Yield transport, opts for all master configured transports
'''
transports = set()
for transport, opts_overrides in six.iteritems(opts.get('transport_opts', {})):
t_opts = dict(opts)
t_opts.update(opts_overrides)
t_opts['transport'] = transport
transports.add(transport)
yield transport, t_opts
if opts['transport'] not in transports:
yield opts['transport'], opts
|
Yield transport, opts for all master configured transports
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/__init__.py#L19-L33
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Encapsulate the different transports available to Salt.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.versions
# Import third party libs
from salt.ext import six
from salt.ext.six.moves import range
log = logging.getLogger(__name__)
# for backwards compatibility
class Channel(object):
@staticmethod
def factory(opts, **kwargs):
salt.utils.versions.warn_until(
'Sodium',
'Stop using salt.transport.Channel and instead use salt.transport.client.ReqChannel',
stacklevel=3
)
from salt.transport.client import ReqChannel
return ReqChannel.factory(opts, **kwargs)
class MessageClientPool(object):
def __init__(self, tgt, opts, args=None, kwargs=None):
sock_pool_size = opts['sock_pool_size'] if 'sock_pool_size' in opts else 1
if sock_pool_size < 1:
log.warning(
'sock_pool_size is not correctly set, the option should be '
'greater than 0 but is instead %s', sock_pool_size
)
sock_pool_size = 1
if args is None:
args = ()
if kwargs is None:
kwargs = {}
self.message_clients = [tgt(*args, **kwargs) for _ in range(sock_pool_size)]
|
saltstack/salt
|
salt/thorium/check.py
|
gt
|
python
|
def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] > value:
ret['result'] = True
return ret
|
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L17-L47
| null |
# -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.stringutils
log = logging.getLogger(__file__)
def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] >= value:
ret['result'] = True
return ret
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] < value:
ret['result'] = True
return ret
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] <= value:
ret['result'] = True
return ret
def eq(name, value):
'''
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] == value:
ret['result'] = True
return ret
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] != value:
ret['result'] = True
return ret
def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
try:
count_compare = count_lt or count_lte or count_eq or\
count_gte or count_gt or count_ne
if count_compare:
occurrences = __reg__[name]['val'].count(value)
log.debug('%s appears %s times', value, occurrences)
ret['result'] = True
if count_lt:
ret['result'] &= occurrences < count_lt
if count_lte:
ret['result'] &= occurrences <= count_lte
if count_eq:
ret['result'] &= occurrences == count_eq
if count_gte:
ret['result'] &= occurrences >= count_gte
if count_gt:
ret['result'] &= occurrences > count_gt
if count_ne:
ret['result'] &= occurrences != count_ne
else:
if value in __reg__[name]['val']:
ret['result'] = True
except TypeError:
pass
return ret
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
for event in __events__:
if salt.utils.stringutils.expr_match(event['tag'], name):
ret['result'] = True
return ret
def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) > value:
ret['result'] = True
return ret
def len_gte(name, value):
'''
Only succeed if the length of the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.len_gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) >= value:
ret['result'] = True
return ret
def len_lt(name, value):
'''
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) < value:
ret['result'] = True
return ret
def len_lte(name, value):
'''
Only succeed if the length of the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.len_lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) <= value:
ret['result'] = True
return ret
def len_eq(name, value):
'''
Only succeed if the length of the given register location is equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) == value:
ret['result'] = True
return ret
def len_ne(name, value):
'''
Only succeed if the length of the given register location is not equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) != value:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/thorium/check.py
|
gte
|
python
|
def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] >= value:
ret['result'] = True
return ret
|
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L50-L80
| null |
# -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.stringutils
log = logging.getLogger(__file__)
def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] > value:
ret['result'] = True
return ret
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] < value:
ret['result'] = True
return ret
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] <= value:
ret['result'] = True
return ret
def eq(name, value):
'''
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] == value:
ret['result'] = True
return ret
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] != value:
ret['result'] = True
return ret
def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
try:
count_compare = count_lt or count_lte or count_eq or\
count_gte or count_gt or count_ne
if count_compare:
occurrences = __reg__[name]['val'].count(value)
log.debug('%s appears %s times', value, occurrences)
ret['result'] = True
if count_lt:
ret['result'] &= occurrences < count_lt
if count_lte:
ret['result'] &= occurrences <= count_lte
if count_eq:
ret['result'] &= occurrences == count_eq
if count_gte:
ret['result'] &= occurrences >= count_gte
if count_gt:
ret['result'] &= occurrences > count_gt
if count_ne:
ret['result'] &= occurrences != count_ne
else:
if value in __reg__[name]['val']:
ret['result'] = True
except TypeError:
pass
return ret
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
for event in __events__:
if salt.utils.stringutils.expr_match(event['tag'], name):
ret['result'] = True
return ret
def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) > value:
ret['result'] = True
return ret
def len_gte(name, value):
'''
Only succeed if the length of the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.len_gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) >= value:
ret['result'] = True
return ret
def len_lt(name, value):
'''
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) < value:
ret['result'] = True
return ret
def len_lte(name, value):
'''
Only succeed if the length of the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.len_lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) <= value:
ret['result'] = True
return ret
def len_eq(name, value):
'''
Only succeed if the length of the given register location is equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) == value:
ret['result'] = True
return ret
def len_ne(name, value):
'''
Only succeed if the length of the given register location is not equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) != value:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/thorium/check.py
|
lt
|
python
|
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] < value:
ret['result'] = True
return ret
|
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L83-L113
| null |
# -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.stringutils
log = logging.getLogger(__file__)
def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] > value:
ret['result'] = True
return ret
def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] >= value:
ret['result'] = True
return ret
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] <= value:
ret['result'] = True
return ret
def eq(name, value):
'''
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] == value:
ret['result'] = True
return ret
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] != value:
ret['result'] = True
return ret
def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
try:
count_compare = count_lt or count_lte or count_eq or\
count_gte or count_gt or count_ne
if count_compare:
occurrences = __reg__[name]['val'].count(value)
log.debug('%s appears %s times', value, occurrences)
ret['result'] = True
if count_lt:
ret['result'] &= occurrences < count_lt
if count_lte:
ret['result'] &= occurrences <= count_lte
if count_eq:
ret['result'] &= occurrences == count_eq
if count_gte:
ret['result'] &= occurrences >= count_gte
if count_gt:
ret['result'] &= occurrences > count_gt
if count_ne:
ret['result'] &= occurrences != count_ne
else:
if value in __reg__[name]['val']:
ret['result'] = True
except TypeError:
pass
return ret
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
for event in __events__:
if salt.utils.stringutils.expr_match(event['tag'], name):
ret['result'] = True
return ret
def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) > value:
ret['result'] = True
return ret
def len_gte(name, value):
'''
Only succeed if the length of the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.len_gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) >= value:
ret['result'] = True
return ret
def len_lt(name, value):
'''
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) < value:
ret['result'] = True
return ret
def len_lte(name, value):
'''
Only succeed if the length of the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.len_lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) <= value:
ret['result'] = True
return ret
def len_eq(name, value):
'''
Only succeed if the length of the given register location is equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) == value:
ret['result'] = True
return ret
def len_ne(name, value):
'''
Only succeed if the length of the given register location is not equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) != value:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/thorium/check.py
|
lte
|
python
|
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] <= value:
ret['result'] = True
return ret
|
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L116-L146
| null |
# -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.stringutils
log = logging.getLogger(__file__)
def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] > value:
ret['result'] = True
return ret
def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] >= value:
ret['result'] = True
return ret
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] < value:
ret['result'] = True
return ret
def eq(name, value):
'''
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] == value:
ret['result'] = True
return ret
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] != value:
ret['result'] = True
return ret
def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
try:
count_compare = count_lt or count_lte or count_eq or\
count_gte or count_gt or count_ne
if count_compare:
occurrences = __reg__[name]['val'].count(value)
log.debug('%s appears %s times', value, occurrences)
ret['result'] = True
if count_lt:
ret['result'] &= occurrences < count_lt
if count_lte:
ret['result'] &= occurrences <= count_lte
if count_eq:
ret['result'] &= occurrences == count_eq
if count_gte:
ret['result'] &= occurrences >= count_gte
if count_gt:
ret['result'] &= occurrences > count_gt
if count_ne:
ret['result'] &= occurrences != count_ne
else:
if value in __reg__[name]['val']:
ret['result'] = True
except TypeError:
pass
return ret
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
for event in __events__:
if salt.utils.stringutils.expr_match(event['tag'], name):
ret['result'] = True
return ret
def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) > value:
ret['result'] = True
return ret
def len_gte(name, value):
'''
Only succeed if the length of the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.len_gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) >= value:
ret['result'] = True
return ret
def len_lt(name, value):
'''
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) < value:
ret['result'] = True
return ret
def len_lte(name, value):
'''
Only succeed if the length of the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.len_lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) <= value:
ret['result'] = True
return ret
def len_eq(name, value):
'''
Only succeed if the length of the given register location is equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) == value:
ret['result'] = True
return ret
def len_ne(name, value):
'''
Only succeed if the length of the given register location is not equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) != value:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/thorium/check.py
|
eq
|
python
|
def eq(name, value):
'''
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] == value:
ret['result'] = True
return ret
|
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L149-L179
| null |
# -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.stringutils
log = logging.getLogger(__file__)
def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] > value:
ret['result'] = True
return ret
def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] >= value:
ret['result'] = True
return ret
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] < value:
ret['result'] = True
return ret
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] <= value:
ret['result'] = True
return ret
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] != value:
ret['result'] = True
return ret
def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
try:
count_compare = count_lt or count_lte or count_eq or\
count_gte or count_gt or count_ne
if count_compare:
occurrences = __reg__[name]['val'].count(value)
log.debug('%s appears %s times', value, occurrences)
ret['result'] = True
if count_lt:
ret['result'] &= occurrences < count_lt
if count_lte:
ret['result'] &= occurrences <= count_lte
if count_eq:
ret['result'] &= occurrences == count_eq
if count_gte:
ret['result'] &= occurrences >= count_gte
if count_gt:
ret['result'] &= occurrences > count_gt
if count_ne:
ret['result'] &= occurrences != count_ne
else:
if value in __reg__[name]['val']:
ret['result'] = True
except TypeError:
pass
return ret
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
for event in __events__:
if salt.utils.stringutils.expr_match(event['tag'], name):
ret['result'] = True
return ret
def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) > value:
ret['result'] = True
return ret
def len_gte(name, value):
'''
Only succeed if the length of the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.len_gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) >= value:
ret['result'] = True
return ret
def len_lt(name, value):
'''
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) < value:
ret['result'] = True
return ret
def len_lte(name, value):
'''
Only succeed if the length of the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.len_lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) <= value:
ret['result'] = True
return ret
def len_eq(name, value):
'''
Only succeed if the length of the given register location is equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) == value:
ret['result'] = True
return ret
def len_ne(name, value):
'''
Only succeed if the length of the given register location is not equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) != value:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/thorium/check.py
|
ne
|
python
|
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] != value:
ret['result'] = True
return ret
|
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L182-L212
| null |
# -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.stringutils
log = logging.getLogger(__file__)
def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] > value:
ret['result'] = True
return ret
def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] >= value:
ret['result'] = True
return ret
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] < value:
ret['result'] = True
return ret
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] <= value:
ret['result'] = True
return ret
def eq(name, value):
'''
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] == value:
ret['result'] = True
return ret
def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
try:
count_compare = count_lt or count_lte or count_eq or\
count_gte or count_gt or count_ne
if count_compare:
occurrences = __reg__[name]['val'].count(value)
log.debug('%s appears %s times', value, occurrences)
ret['result'] = True
if count_lt:
ret['result'] &= occurrences < count_lt
if count_lte:
ret['result'] &= occurrences <= count_lte
if count_eq:
ret['result'] &= occurrences == count_eq
if count_gte:
ret['result'] &= occurrences >= count_gte
if count_gt:
ret['result'] &= occurrences > count_gt
if count_ne:
ret['result'] &= occurrences != count_ne
else:
if value in __reg__[name]['val']:
ret['result'] = True
except TypeError:
pass
return ret
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
for event in __events__:
if salt.utils.stringutils.expr_match(event['tag'], name):
ret['result'] = True
return ret
def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) > value:
ret['result'] = True
return ret
def len_gte(name, value):
'''
Only succeed if the length of the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.len_gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) >= value:
ret['result'] = True
return ret
def len_lt(name, value):
'''
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) < value:
ret['result'] = True
return ret
def len_lte(name, value):
'''
Only succeed if the length of the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.len_lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) <= value:
ret['result'] = True
return ret
def len_eq(name, value):
'''
Only succeed if the length of the given register location is equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) == value:
ret['result'] = True
return ret
def len_ne(name, value):
'''
Only succeed if the length of the given register location is not equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) != value:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/thorium/check.py
|
contains
|
python
|
def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
try:
count_compare = count_lt or count_lte or count_eq or\
count_gte or count_gt or count_ne
if count_compare:
occurrences = __reg__[name]['val'].count(value)
log.debug('%s appears %s times', value, occurrences)
ret['result'] = True
if count_lt:
ret['result'] &= occurrences < count_lt
if count_lte:
ret['result'] &= occurrences <= count_lte
if count_eq:
ret['result'] &= occurrences == count_eq
if count_gte:
ret['result'] &= occurrences >= count_gte
if count_gt:
ret['result'] &= occurrences > count_gt
if count_ne:
ret['result'] &= occurrences != count_ne
else:
if value in __reg__[name]['val']:
ret['result'] = True
except TypeError:
pass
return ret
|
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L215-L274
| null |
# -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.stringutils
log = logging.getLogger(__file__)
def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] > value:
ret['result'] = True
return ret
def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] >= value:
ret['result'] = True
return ret
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] < value:
ret['result'] = True
return ret
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] <= value:
ret['result'] = True
return ret
def eq(name, value):
'''
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] == value:
ret['result'] = True
return ret
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] != value:
ret['result'] = True
return ret
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
for event in __events__:
if salt.utils.stringutils.expr_match(event['tag'], name):
ret['result'] = True
return ret
def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) > value:
ret['result'] = True
return ret
def len_gte(name, value):
'''
Only succeed if the length of the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.len_gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) >= value:
ret['result'] = True
return ret
def len_lt(name, value):
'''
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) < value:
ret['result'] = True
return ret
def len_lte(name, value):
'''
Only succeed if the length of the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.len_lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) <= value:
ret['result'] = True
return ret
def len_eq(name, value):
'''
Only succeed if the length of the given register location is equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) == value:
ret['result'] = True
return ret
def len_ne(name, value):
'''
Only succeed if the length of the given register location is not equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) != value:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/thorium/check.py
|
event
|
python
|
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
for event in __events__:
if salt.utils.stringutils.expr_match(event['tag'], name):
ret['result'] = True
return ret
|
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L277-L305
|
[
"def expr_match(line, expr):\n '''\n Checks whether or not the passed value matches the specified expression.\n Tries to match expr first as a glob using fnmatch.fnmatch(), and then tries\n to match expr as a regular expression. Originally designed to match minion\n IDs for whitelists/blacklists.\n\n Note that this also does exact matches, as fnmatch.fnmatch() will return\n ``True`` when no glob characters are used and the string is an exact match:\n\n .. code-block:: python\n\n >>> fnmatch.fnmatch('foo', 'foo')\n True\n '''\n try:\n if fnmatch.fnmatch(line, expr):\n return True\n try:\n if re.match(r'\\A{0}\\Z'.format(expr), line):\n return True\n except re.error:\n pass\n except TypeError:\n log.exception('Value %r or expression %r is not a string', line, expr)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.stringutils
log = logging.getLogger(__file__)
def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] > value:
ret['result'] = True
return ret
def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] >= value:
ret['result'] = True
return ret
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] < value:
ret['result'] = True
return ret
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] <= value:
ret['result'] = True
return ret
def eq(name, value):
'''
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] == value:
ret['result'] = True
return ret
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] != value:
ret['result'] = True
return ret
def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
try:
count_compare = count_lt or count_lte or count_eq or\
count_gte or count_gt or count_ne
if count_compare:
occurrences = __reg__[name]['val'].count(value)
log.debug('%s appears %s times', value, occurrences)
ret['result'] = True
if count_lt:
ret['result'] &= occurrences < count_lt
if count_lte:
ret['result'] &= occurrences <= count_lte
if count_eq:
ret['result'] &= occurrences == count_eq
if count_gte:
ret['result'] &= occurrences >= count_gte
if count_gt:
ret['result'] &= occurrences > count_gt
if count_ne:
ret['result'] &= occurrences != count_ne
else:
if value in __reg__[name]['val']:
ret['result'] = True
except TypeError:
pass
return ret
def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) > value:
ret['result'] = True
return ret
def len_gte(name, value):
'''
Only succeed if the length of the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.len_gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) >= value:
ret['result'] = True
return ret
def len_lt(name, value):
'''
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) < value:
ret['result'] = True
return ret
def len_lte(name, value):
'''
Only succeed if the length of the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.len_lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) <= value:
ret['result'] = True
return ret
def len_eq(name, value):
'''
Only succeed if the length of the given register location is equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) == value:
ret['result'] = True
return ret
def len_ne(name, value):
'''
Only succeed if the length of the given register location is not equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) != value:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/thorium/check.py
|
len_gt
|
python
|
def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) > value:
ret['result'] = True
return ret
|
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L308-L338
| null |
# -*- coding: utf-8 -*-
'''
The check Thorium state is used to create gateways to commands, the checks
make it easy to make states that watch registers for changes and then just
succeed or fail based on the state of the register, this creates the pattern
of having a command execution get gated by a check state via a requisite.
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.stringutils
log = logging.getLogger(__file__)
def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] > value:
ret['result'] = True
return ret
def gte(name, value):
'''
Only succeed if the value in the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] >= value:
ret['result'] = True
return ret
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] < value:
ret['result'] = True
return ret
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] <= value:
ret['result'] = True
return ret
def eq(name, value):
'''
Only succeed if the value in the given register location is equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] == value:
ret['result'] = True
return ret
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if __reg__[name]['val'] != value:
ret['result'] = True
return ret
def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.contains:
- value: itni
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
try:
count_compare = count_lt or count_lte or count_eq or\
count_gte or count_gt or count_ne
if count_compare:
occurrences = __reg__[name]['val'].count(value)
log.debug('%s appears %s times', value, occurrences)
ret['result'] = True
if count_lt:
ret['result'] &= occurrences < count_lt
if count_lte:
ret['result'] &= occurrences <= count_lte
if count_eq:
ret['result'] &= occurrences == count_eq
if count_gte:
ret['result'] &= occurrences >= count_gte
if count_gt:
ret['result'] &= occurrences > count_gt
if count_ne:
ret['result'] &= occurrences != count_ne
else:
if value in __reg__[name]['val']:
ret['result'] = True
except TypeError:
pass
return ret
def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: salt/foo/*/bar
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
for event in __events__:
if salt.utils.stringutils.expr_match(event['tag'], name):
ret['result'] = True
return ret
def len_gte(name, value):
'''
Only succeed if the length of the given register location is greater or equal
than the given value
USAGE:
.. code-block:: yaml
foo:
check.len_gte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) >= value:
ret['result'] = True
return ret
def len_lt(name, value):
'''
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) < value:
ret['result'] = True
return ret
def len_lte(name, value):
'''
Only succeed if the length of the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.len_lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) <= value:
ret['result'] = True
return ret
def len_eq(name, value):
'''
Only succeed if the length of the given register location is equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_eq:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) == value:
ret['result'] = True
return ret
def len_ne(name, value):
'''
Only succeed if the length of the given register location is not equal to
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
- check: foo
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
if name not in __reg__:
ret['result'] = False
ret['comment'] = 'Value {0} not in register'.format(name)
return ret
if len(__reg__[name]['val']) != value:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/modules/napalm_users.py
|
set_users
|
python
|
def set_users(users, test=False, commit=True, **kwargs): # pylint: disable=unused-argument
'''
Configures users on network devices.
:param users: Dictionary formatted as the output of the function config()
:param test: Dry run? If set as True, will apply the config, discard and
return the changes. Default: False
:param commit: Commit? (default: True) Sometimes it is not needed to commit
the config immediately after loading the changes. E.g.: a state loads a
couple of parts (add / remove / update) and would not be optimal to
commit after each operation. Also, from the CLI when the user needs to
apply the similar changes before committing, can specify commit=False
and will not discard the config.
:raise MergeConfigException: If there is an error on the configuration sent.
:return a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is `False` only
in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still `True` and so will be
the `already_configured` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' users.set_users "{'mircea': {}}"
'''
return __salt__['net.load_template']('set_users',
users=users,
test=test,
commit=commit,
inherit_napalm_device=napalm_device)
|
Configures users on network devices.
:param users: Dictionary formatted as the output of the function config()
:param test: Dry run? If set as True, will apply the config, discard and
return the changes. Default: False
:param commit: Commit? (default: True) Sometimes it is not needed to commit
the config immediately after loading the changes. E.g.: a state loads a
couple of parts (add / remove / update) and would not be optimal to
commit after each operation. Also, from the CLI when the user needs to
apply the similar changes before committing, can specify commit=False
and will not discard the config.
:raise MergeConfigException: If there is an error on the configuration sent.
:return a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is `False` only
in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still `True` and so will be
the `already_configured` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' users.set_users "{'mircea': {}}"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_users.py#L102-L141
| null |
# -*- coding: utf-8 -*-
'''
NAPALM Users
============
Manages the configuration of the users on network devices.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`NAPALM proxy minion <salt.proxy.napalm>`
.. seealso::
:mod:`Users management state <salt.states.netusers>`
.. versionadded:: 2016.11.0
'''
from __future__ import absolute_import, unicode_literals, print_function
import logging
log = logging.getLogger(__file__)
# import NAPALM utils
import salt.utils.napalm
from salt.utils.napalm import proxy_napalm_wrap
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'users'
__proxyenabled__ = ['napalm']
__virtual_aliases__ = ('napalm_users',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@proxy_napalm_wrap
def config(**kwargs): # pylint: disable=unused-argument
'''
Returns the configuration of the users on the device
CLI Example:
.. code-block:: bash
salt '*' users.config
Output example:
.. code-block:: python
{
'mircea': {
'level': 15,
'password': '$1$0P70xKPa$4jt5/10cBTckk6I/w/',
'sshkeys': [
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC4pFn+shPwTb2yELO4L7NtQrKOJXNeCl1je\
l9STXVaGnRAnuc2PXl35vnWmcUq6YbUEcgUTRzzXfmelJKuVJTJIlMXii7h2xkbQp0YZIEs4P\
8ipwnRBAxFfk/ZcDsN3mjep4/yjN56ejk345jhk345jk345jk341p3A/9LIL7l6YewLBCwJj6\
D+fWSJ0/YW+7oH17Fk2HH+tw0L5PcWLHkwA4t60iXn16qDbIk/ze6jv2hDGdCdz7oYQeCE55C\
CHOHMJWYfN3jcL4s0qv8/u6Ka1FVkV7iMmro7ChThoV/5snI4Ljf2wKqgHH7TfNaCfpU0WvHA\
nTs8zhOrGScSrtb mircea@master-roshi'
]
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_users',
**{
}
)
@proxy_napalm_wrap
# pylint: disable=undefined-variable
@proxy_napalm_wrap
def delete_users(users, test=False, commit=True, **kwargs): # pylint: disable=unused-argument
'''
Removes users from the configuration of network devices.
:param users: Dictionary formatted as the output of the function config()
:param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False
:param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately
after loading the changes. E.g.: a state loads a couple of parts (add / remove / update)
and would not be optimal to commit after each operation.
Also, from the CLI when the user needs to apply the similar changes before committing,
can specify commit=False and will not discard the config.
:raise MergeConfigException: If there is an error on the configuration sent.
:return a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is `False`
only in case of failure. In case there are no changes to be applied
and successfully performs all operations it is still `True` and so
will be the `already_configured` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' users.delete_users "{'mircea': {}}"
'''
return __salt__['net.load_template']('delete_users',
users=users,
test=test,
commit=commit,
inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
|
saltstack/salt
|
salt/cloud/clouds/virtualbox.py
|
map_clonemode
|
python
|
def map_clonemode(vm_info):
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info['clonemode'] in mode_map:
return mode_map[vm_info['clonemode']]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(','.join(mode_map.keys()))
)
|
Convert the virtualbox config file values for clone_mode into the integers the API requires
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/virtualbox.py#L92-L113
| null |
# -*- coding: utf-8 -*-
'''
A salt cloud provider that lets you use virtualbox on your machine
and act as a cloud.
:depends: vboxapi
For now this will only clone existing VMs. It's best to create a template
from which we will clone.
Followed
https://docs.saltstack.com/en/latest/topics/cloud/cloud.html#non-libcloud-based-modules
to create this.
Dicts provided by salt:
__opts__ : contains the options used to run Salt Cloud,
as well as a set of configuration and environment variables
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
from salt.exceptions import SaltCloudSystemExit
import salt.config as config
# Import Third Party Libs
try:
import vboxapi # pylint: disable=unused-import
from salt.utils.virtualbox import (
vb_list_machines,
vb_clone_vm,
vb_machine_exists,
vb_destroy_machine,
vb_get_machine,
vb_stop_vm,
treat_machine_dict,
vb_start_vm,
vb_wait_for_network_address
)
HAS_VBOX = True
except ImportError:
HAS_VBOX = False
log = logging.getLogger(__name__)
# The name salt will identify the lib by
__virtualname__ = 'virtualbox'
#if no clone mode is specified in the virtualbox profile
#then default to 0 which was the old default value
DEFAULT_CLONE_MODE = 0
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_VBOX:
return False, 'The virtualbox driver cannot be loaded: \'vboxapi\' is not installed.'
if get_configured_provider() is False:
return False, 'The virtualbox driver cannot be loaded: \'virtualbox\' provider is not configured.'
# If the name of the driver used does not match the filename,
# then that name should be returned instead of True.
return __virtualname__
def get_configured_provider():
"""
Return the first configured instance.
"""
configured = config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
() # keys we need from the provider configuration
)
return configured
def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires the event ``salt/cloud/vm_name/creating``, with the
payload containing the names of the VM, profile, and provider.
@param vm_info
.. code-block:: text
{
name: <str>
profile: <dict>
driver: <provider>:<profile>
clonefrom: <vm_name>
clonemode: <mode> (default: state, choices: state, child, all)
}
@type vm_info dict
@return dict of resulting vm. !!!Passwords can and should be included!!!
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_info['profile'] and config.is_profile_configured(
__opts__,
__active_provider_name__ or 'virtualbox',
vm_info['profile']
) is False:
return False
except AttributeError:
pass
vm_name = vm_info["name"]
deploy = config.get_cloud_config_value(
'deploy', vm_info, __opts__, search_global=False, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_info, __opts__, default=60
)
boot_timeout = config.get_cloud_config_value(
'boot_timeout', vm_info, __opts__, default=60 * 1000
)
power = config.get_cloud_config_value(
'power_on', vm_info, __opts__, default=False
)
key_filename = config.get_cloud_config_value(
'private_key', vm_info, __opts__, search_global=False, default=None
)
clone_mode = map_clonemode(vm_info)
wait_for_pattern = vm_info['waitforpattern'] if 'waitforpattern' in vm_info.keys() else None
interface_index = vm_info['interfaceindex'] if 'interfaceindex' in vm_info.keys() else 0
log.debug("Going to fire event: starting create")
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('creating', vm_info, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# to create the virtual machine.
request_kwargs = {
'name': vm_info['name'],
'clone_from': vm_info['clonefrom'],
'clone_mode': clone_mode
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('requesting', request_kwargs, list(request_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_result = vb_clone_vm(**request_kwargs)
# Booting and deploying if needed
if power:
vb_start_vm(vm_name, timeout=boot_timeout)
ips = vb_wait_for_network_address(wait_for_ip_timeout, machine_name=vm_name, wait_for_pattern=wait_for_pattern)
if ips:
ip = ips[interface_index]
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_info['key_filename'] = key_filename
vm_info['ssh_host'] = ip
res = __utils__['cloud.bootstrap'](vm_info, __opts__)
vm_result.update(res)
__utils__['cloud.fire_event'](
'event',
'created machine',
'salt/cloud/{0}/created'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('created', vm_result, list(vm_result)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Passwords should be included in this object!!
return vm_result
def list_nodes_full(kwargs=None, call=None):
"""
All information available about all nodes should be returned in this function.
The fields in the list_nodes() function should also be returned,
even if they would not normally be provided by the cloud provider.
This is because some functions both within Salt and 3rd party will break if an expected field is not present.
This function is normally called with the -F option:
.. code-block:: bash
salt-cloud -F
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
machines = {}
# TODO ask for the correct attributes e.g state and private_ips
for machine in vb_list_machines():
name = machine.get("name")
if name:
machines[name] = treat_machine_dict(machine)
del machine["name"]
return machines
def list_nodes(kwargs=None, call=None):
"""
This function returns a list of nodes available on this cloud provider, using the following fields:
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
No other fields should be returned in this function, and all of these fields should be returned, even if empty.
The private_ips and public_ips fields should always be of a list type, even if empty,
and the other fields should always be of a str type.
This function is normally called with the -Q option:
.. code-block:: bash
salt-cloud -Q
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
attributes = [
"id",
"image",
"size",
"state",
"private_ips",
"public_ips",
]
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), attributes, call,
)
def list_nodes_select(call=None):
"""
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), __opts__['query.selection'], call,
)
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if not vb_machine_exists(name):
return "{0} doesn't exist and can't be deleted".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vb_destroy_machine(name)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def start(name, call=None):
'''
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
'''
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Starting machine: %s", name)
vb_start_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def stop(name, call=None):
"""
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
"""
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Stopping machine: %s", name)
vb_stop_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def show_image(kwargs, call=None):
"""
Show the details of an image
"""
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_machine(name)
ret = {
machine["name"]: treat_machine_dict(machine)
}
del machine["name"]
return ret
|
saltstack/salt
|
salt/cloud/clouds/virtualbox.py
|
create
|
python
|
def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires the event ``salt/cloud/vm_name/creating``, with the
payload containing the names of the VM, profile, and provider.
@param vm_info
.. code-block:: text
{
name: <str>
profile: <dict>
driver: <provider>:<profile>
clonefrom: <vm_name>
clonemode: <mode> (default: state, choices: state, child, all)
}
@type vm_info dict
@return dict of resulting vm. !!!Passwords can and should be included!!!
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_info['profile'] and config.is_profile_configured(
__opts__,
__active_provider_name__ or 'virtualbox',
vm_info['profile']
) is False:
return False
except AttributeError:
pass
vm_name = vm_info["name"]
deploy = config.get_cloud_config_value(
'deploy', vm_info, __opts__, search_global=False, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_info, __opts__, default=60
)
boot_timeout = config.get_cloud_config_value(
'boot_timeout', vm_info, __opts__, default=60 * 1000
)
power = config.get_cloud_config_value(
'power_on', vm_info, __opts__, default=False
)
key_filename = config.get_cloud_config_value(
'private_key', vm_info, __opts__, search_global=False, default=None
)
clone_mode = map_clonemode(vm_info)
wait_for_pattern = vm_info['waitforpattern'] if 'waitforpattern' in vm_info.keys() else None
interface_index = vm_info['interfaceindex'] if 'interfaceindex' in vm_info.keys() else 0
log.debug("Going to fire event: starting create")
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('creating', vm_info, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# to create the virtual machine.
request_kwargs = {
'name': vm_info['name'],
'clone_from': vm_info['clonefrom'],
'clone_mode': clone_mode
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('requesting', request_kwargs, list(request_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_result = vb_clone_vm(**request_kwargs)
# Booting and deploying if needed
if power:
vb_start_vm(vm_name, timeout=boot_timeout)
ips = vb_wait_for_network_address(wait_for_ip_timeout, machine_name=vm_name, wait_for_pattern=wait_for_pattern)
if ips:
ip = ips[interface_index]
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_info['key_filename'] = key_filename
vm_info['ssh_host'] = ip
res = __utils__['cloud.bootstrap'](vm_info, __opts__)
vm_result.update(res)
__utils__['cloud.fire_event'](
'event',
'created machine',
'salt/cloud/{0}/created'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('created', vm_result, list(vm_result)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Passwords should be included in this object!!
return vm_result
|
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires the event ``salt/cloud/vm_name/creating``, with the
payload containing the names of the VM, profile, and provider.
@param vm_info
.. code-block:: text
{
name: <str>
profile: <dict>
driver: <provider>:<profile>
clonefrom: <vm_name>
clonemode: <mode> (default: state, choices: state, child, all)
}
@type vm_info dict
@return dict of resulting vm. !!!Passwords can and should be included!!!
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/virtualbox.py#L116-L228
|
[
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def is_profile_configured(opts, provider, profile_name, vm_=None):\n '''\n Check if the requested profile contains the minimum required parameters for\n a profile.\n\n Required parameters include image and provider for all drivers, while some\n drivers also require size keys.\n\n .. versionadded:: 2015.8.0\n '''\n # Standard dict keys required by all drivers.\n required_keys = ['provider']\n alias, driver = provider.split(':')\n\n # Most drivers need an image to be specified, but some do not.\n non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']\n\n # Most drivers need a size, but some do not.\n non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',\n 'softlayer', 'softlayer_hw', 'vmware', 'vsphere',\n 'virtualbox', 'libvirt', 'oneandone', 'profitbricks']\n\n provider_key = opts['providers'][alias][driver]\n profile_key = opts['providers'][alias][driver]['profiles'][profile_name]\n\n # If cloning on Linode, size and image are not necessary.\n # They are obtained from the to-be-cloned VM.\n if driver == 'linode' and profile_key.get('clonefrom', False):\n non_image_drivers.append('linode')\n non_size_drivers.append('linode')\n elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):\n non_image_drivers.append('gce')\n\n # If cloning on VMware, specifying image is not necessary.\n if driver == 'vmware' and 'image' not in list(profile_key.keys()):\n non_image_drivers.append('vmware')\n\n if driver not in non_image_drivers:\n required_keys.append('image')\n if driver == 'vmware':\n required_keys.append('datastore')\n elif driver in ['linode', 'virtualbox']:\n required_keys.append('clonefrom')\n elif driver == 'nova':\n nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']\n if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):\n required_keys.extend(nova_image_keys)\n\n if driver not in non_size_drivers:\n required_keys.append('size')\n\n # Check if required fields are supplied in the provider config. If they\n # are present, remove it from the required_keys list.\n for item in list(required_keys):\n if item in provider_key:\n required_keys.remove(item)\n\n # If a vm_ dict was passed in, use that information to get any other configs\n # that we might have missed thus far, such as a option provided in a map file.\n if vm_:\n for item in list(required_keys):\n if item in vm_:\n required_keys.remove(item)\n\n # Check for remaining required parameters in the profile config.\n for item in required_keys:\n if profile_key.get(item, None) is None:\n # There's at least one required configuration item which is not set.\n log.error(\n \"The required '%s' configuration setting is missing from \"\n \"the '%s' profile, which is configured under the '%s' alias.\",\n item, profile_name, alias\n )\n return False\n\n return True\n",
"def vb_clone_vm(\n name=None,\n clone_from=None,\n clone_mode=0,\n timeout=10000,\n **kwargs\n):\n '''\n Tells virtualbox to create a VM by cloning from an existing one\n\n @param name: Name for the new VM\n @type name: str\n @param clone_from:\n @type clone_from: str\n @param timeout: maximum time in milliseconds to wait or -1 to wait indefinitely\n @type timeout: int\n @return dict of resulting VM\n '''\n vbox = vb_get_box()\n log.info('Clone virtualbox machine %s from %s', name, clone_from)\n\n source_machine = vbox.findMachine(clone_from)\n\n groups = None\n os_type_id = 'Other'\n new_machine = vbox.createMachine(\n None, # Settings file\n name,\n groups,\n os_type_id,\n None # flags\n )\n\n progress = source_machine.cloneTo(\n new_machine,\n clone_mode, # CloneMode\n None # CloneOptions : None = Full?\n )\n\n progress.waitForCompletion(timeout)\n log.info('Finished cloning %s from %s', name, clone_from)\n\n vbox.registerMachine(new_machine)\n\n return vb_xpcom_to_attribute_dict(new_machine, 'IMachine')\n",
"def vb_start_vm(name=None, timeout=10000, **kwargs):\n '''\n Tells Virtualbox to start up a VM.\n Blocking function!\n\n @param name:\n @type name: str\n @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely\n @type timeout: int\n @return untreated dict of started VM\n '''\n # Time tracking\n start_time = time.time()\n timeout_in_seconds = timeout / 1000\n max_time = start_time + timeout_in_seconds\n\n vbox = vb_get_box()\n machine = vbox.findMachine(name)\n session = _virtualboxManager.getSessionObject(vbox)\n\n log.info('Starting machine %s in state %s', name, vb_machinestate_to_str(machine.state))\n try:\n # Keep trying to start a machine\n args = (machine, session)\n progress = wait_for(_start_machine, timeout=timeout_in_seconds, func_args=args)\n if not progress:\n progress = machine.launchVMProcess(session, '', '')\n\n # We already waited for stuff, don't push it\n time_left = max_time - time.time()\n progress.waitForCompletion(time_left * 1000)\n finally:\n _virtualboxManager.closeMachineSession(session)\n\n # The session state should best be unlocked otherwise subsequent calls might cause problems\n time_left = max_time - time.time()\n vb_wait_for_session_state(session, timeout=time_left)\n log.info('Started machine %s', name)\n\n return vb_xpcom_to_attribute_dict(machine, 'IMachine')\n",
"def vb_wait_for_network_address(timeout, step=None, machine_name=None, machine=None, wait_for_pattern=None):\n '''\n Wait until a machine has a network address to return or quit after the timeout\n\n @param timeout: in seconds\n @type timeout: float\n @param step: How regularly we want to check for ips (in seconds)\n @type step: float\n @param machine_name:\n @type machine_name: str\n @param machine:\n @type machine: IMachine\n @type wait_for_pattern: str\n @param wait_for_pattern:\n @type machine: str\n @return:\n @rtype: list\n '''\n kwargs = {\n 'machine_name': machine_name,\n 'machine': machine,\n 'wait_for_pattern': wait_for_pattern\n }\n return wait_for(vb_get_network_addresses, timeout=timeout, step=step, default=[], func_kwargs=kwargs)\n",
"def map_clonemode(vm_info):\n \"\"\"\n Convert the virtualbox config file values for clone_mode into the integers the API requires\n \"\"\"\n mode_map = {\n 'state': 0,\n 'child': 1,\n 'all': 2\n }\n\n if not vm_info:\n return DEFAULT_CLONE_MODE\n\n if 'clonemode' not in vm_info:\n return DEFAULT_CLONE_MODE\n\n if vm_info['clonemode'] in mode_map:\n return mode_map[vm_info['clonemode']]\n else:\n raise SaltCloudSystemExit(\n \"Illegal clonemode for virtualbox profile. Legal values are: {}\".format(','.join(mode_map.keys()))\n )\n"
] |
# -*- coding: utf-8 -*-
'''
A salt cloud provider that lets you use virtualbox on your machine
and act as a cloud.
:depends: vboxapi
For now this will only clone existing VMs. It's best to create a template
from which we will clone.
Followed
https://docs.saltstack.com/en/latest/topics/cloud/cloud.html#non-libcloud-based-modules
to create this.
Dicts provided by salt:
__opts__ : contains the options used to run Salt Cloud,
as well as a set of configuration and environment variables
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
from salt.exceptions import SaltCloudSystemExit
import salt.config as config
# Import Third Party Libs
try:
import vboxapi # pylint: disable=unused-import
from salt.utils.virtualbox import (
vb_list_machines,
vb_clone_vm,
vb_machine_exists,
vb_destroy_machine,
vb_get_machine,
vb_stop_vm,
treat_machine_dict,
vb_start_vm,
vb_wait_for_network_address
)
HAS_VBOX = True
except ImportError:
HAS_VBOX = False
log = logging.getLogger(__name__)
# The name salt will identify the lib by
__virtualname__ = 'virtualbox'
#if no clone mode is specified in the virtualbox profile
#then default to 0 which was the old default value
DEFAULT_CLONE_MODE = 0
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_VBOX:
return False, 'The virtualbox driver cannot be loaded: \'vboxapi\' is not installed.'
if get_configured_provider() is False:
return False, 'The virtualbox driver cannot be loaded: \'virtualbox\' provider is not configured.'
# If the name of the driver used does not match the filename,
# then that name should be returned instead of True.
return __virtualname__
def get_configured_provider():
"""
Return the first configured instance.
"""
configured = config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
() # keys we need from the provider configuration
)
return configured
def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
"""
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info['clonemode'] in mode_map:
return mode_map[vm_info['clonemode']]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(','.join(mode_map.keys()))
)
def list_nodes_full(kwargs=None, call=None):
"""
All information available about all nodes should be returned in this function.
The fields in the list_nodes() function should also be returned,
even if they would not normally be provided by the cloud provider.
This is because some functions both within Salt and 3rd party will break if an expected field is not present.
This function is normally called with the -F option:
.. code-block:: bash
salt-cloud -F
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
machines = {}
# TODO ask for the correct attributes e.g state and private_ips
for machine in vb_list_machines():
name = machine.get("name")
if name:
machines[name] = treat_machine_dict(machine)
del machine["name"]
return machines
def list_nodes(kwargs=None, call=None):
"""
This function returns a list of nodes available on this cloud provider, using the following fields:
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
No other fields should be returned in this function, and all of these fields should be returned, even if empty.
The private_ips and public_ips fields should always be of a list type, even if empty,
and the other fields should always be of a str type.
This function is normally called with the -Q option:
.. code-block:: bash
salt-cloud -Q
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
attributes = [
"id",
"image",
"size",
"state",
"private_ips",
"public_ips",
]
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), attributes, call,
)
def list_nodes_select(call=None):
"""
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), __opts__['query.selection'], call,
)
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if not vb_machine_exists(name):
return "{0} doesn't exist and can't be deleted".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vb_destroy_machine(name)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def start(name, call=None):
'''
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
'''
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Starting machine: %s", name)
vb_start_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def stop(name, call=None):
"""
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
"""
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Stopping machine: %s", name)
vb_stop_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def show_image(kwargs, call=None):
"""
Show the details of an image
"""
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_machine(name)
ret = {
machine["name"]: treat_machine_dict(machine)
}
del machine["name"]
return ret
|
saltstack/salt
|
salt/cloud/clouds/virtualbox.py
|
list_nodes_full
|
python
|
def list_nodes_full(kwargs=None, call=None):
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
machines = {}
# TODO ask for the correct attributes e.g state and private_ips
for machine in vb_list_machines():
name = machine.get("name")
if name:
machines[name] = treat_machine_dict(machine)
del machine["name"]
return machines
|
All information available about all nodes should be returned in this function.
The fields in the list_nodes() function should also be returned,
even if they would not normally be provided by the cloud provider.
This is because some functions both within Salt and 3rd party will break if an expected field is not present.
This function is normally called with the -F option:
.. code-block:: bash
salt-cloud -F
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/virtualbox.py#L231-L268
|
[
"def vb_list_machines(**kwargs):\n '''\n Which machines does the hypervisor have\n @param kwargs: Passed to vb_xpcom_to_attribute_dict to filter the attributes\n @type kwargs: dict\n @return: Untreated dicts of the machines known to the hypervisor\n @rtype: [{}]\n '''\n manager = vb_get_manager()\n machines = manager.getArray(vb_get_box(), 'machines')\n return [\n vb_xpcom_to_attribute_dict(machine, 'IMachine', **kwargs)\n for machine in machines\n ]\n",
"def treat_machine_dict(machine):\n '''\n Make machine presentable for outside world.\n\n !!!Modifies the input machine!!!\n\n @param machine:\n @type machine: dict\n @return: the modified input machine\n @rtype: dict\n '''\n machine.update({\n 'id': machine.get('id', ''),\n 'image': machine.get('image', ''),\n 'size': '{0} MB'.format(machine.get('memorySize', 0)),\n 'state': machine_get_machinestate_str(machine),\n 'private_ips': [],\n 'public_ips': [],\n })\n\n # Replaced keys\n if 'memorySize' in machine:\n del machine['memorySize']\n return machine\n"
] |
# -*- coding: utf-8 -*-
'''
A salt cloud provider that lets you use virtualbox on your machine
and act as a cloud.
:depends: vboxapi
For now this will only clone existing VMs. It's best to create a template
from which we will clone.
Followed
https://docs.saltstack.com/en/latest/topics/cloud/cloud.html#non-libcloud-based-modules
to create this.
Dicts provided by salt:
__opts__ : contains the options used to run Salt Cloud,
as well as a set of configuration and environment variables
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
from salt.exceptions import SaltCloudSystemExit
import salt.config as config
# Import Third Party Libs
try:
import vboxapi # pylint: disable=unused-import
from salt.utils.virtualbox import (
vb_list_machines,
vb_clone_vm,
vb_machine_exists,
vb_destroy_machine,
vb_get_machine,
vb_stop_vm,
treat_machine_dict,
vb_start_vm,
vb_wait_for_network_address
)
HAS_VBOX = True
except ImportError:
HAS_VBOX = False
log = logging.getLogger(__name__)
# The name salt will identify the lib by
__virtualname__ = 'virtualbox'
#if no clone mode is specified in the virtualbox profile
#then default to 0 which was the old default value
DEFAULT_CLONE_MODE = 0
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_VBOX:
return False, 'The virtualbox driver cannot be loaded: \'vboxapi\' is not installed.'
if get_configured_provider() is False:
return False, 'The virtualbox driver cannot be loaded: \'virtualbox\' provider is not configured.'
# If the name of the driver used does not match the filename,
# then that name should be returned instead of True.
return __virtualname__
def get_configured_provider():
"""
Return the first configured instance.
"""
configured = config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
() # keys we need from the provider configuration
)
return configured
def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
"""
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info['clonemode'] in mode_map:
return mode_map[vm_info['clonemode']]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(','.join(mode_map.keys()))
)
def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires the event ``salt/cloud/vm_name/creating``, with the
payload containing the names of the VM, profile, and provider.
@param vm_info
.. code-block:: text
{
name: <str>
profile: <dict>
driver: <provider>:<profile>
clonefrom: <vm_name>
clonemode: <mode> (default: state, choices: state, child, all)
}
@type vm_info dict
@return dict of resulting vm. !!!Passwords can and should be included!!!
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_info['profile'] and config.is_profile_configured(
__opts__,
__active_provider_name__ or 'virtualbox',
vm_info['profile']
) is False:
return False
except AttributeError:
pass
vm_name = vm_info["name"]
deploy = config.get_cloud_config_value(
'deploy', vm_info, __opts__, search_global=False, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_info, __opts__, default=60
)
boot_timeout = config.get_cloud_config_value(
'boot_timeout', vm_info, __opts__, default=60 * 1000
)
power = config.get_cloud_config_value(
'power_on', vm_info, __opts__, default=False
)
key_filename = config.get_cloud_config_value(
'private_key', vm_info, __opts__, search_global=False, default=None
)
clone_mode = map_clonemode(vm_info)
wait_for_pattern = vm_info['waitforpattern'] if 'waitforpattern' in vm_info.keys() else None
interface_index = vm_info['interfaceindex'] if 'interfaceindex' in vm_info.keys() else 0
log.debug("Going to fire event: starting create")
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('creating', vm_info, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# to create the virtual machine.
request_kwargs = {
'name': vm_info['name'],
'clone_from': vm_info['clonefrom'],
'clone_mode': clone_mode
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('requesting', request_kwargs, list(request_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_result = vb_clone_vm(**request_kwargs)
# Booting and deploying if needed
if power:
vb_start_vm(vm_name, timeout=boot_timeout)
ips = vb_wait_for_network_address(wait_for_ip_timeout, machine_name=vm_name, wait_for_pattern=wait_for_pattern)
if ips:
ip = ips[interface_index]
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_info['key_filename'] = key_filename
vm_info['ssh_host'] = ip
res = __utils__['cloud.bootstrap'](vm_info, __opts__)
vm_result.update(res)
__utils__['cloud.fire_event'](
'event',
'created machine',
'salt/cloud/{0}/created'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('created', vm_result, list(vm_result)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Passwords should be included in this object!!
return vm_result
def list_nodes(kwargs=None, call=None):
"""
This function returns a list of nodes available on this cloud provider, using the following fields:
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
No other fields should be returned in this function, and all of these fields should be returned, even if empty.
The private_ips and public_ips fields should always be of a list type, even if empty,
and the other fields should always be of a str type.
This function is normally called with the -Q option:
.. code-block:: bash
salt-cloud -Q
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
attributes = [
"id",
"image",
"size",
"state",
"private_ips",
"public_ips",
]
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), attributes, call,
)
def list_nodes_select(call=None):
"""
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), __opts__['query.selection'], call,
)
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if not vb_machine_exists(name):
return "{0} doesn't exist and can't be deleted".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vb_destroy_machine(name)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def start(name, call=None):
'''
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
'''
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Starting machine: %s", name)
vb_start_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def stop(name, call=None):
"""
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
"""
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Stopping machine: %s", name)
vb_stop_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def show_image(kwargs, call=None):
"""
Show the details of an image
"""
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_machine(name)
ret = {
machine["name"]: treat_machine_dict(machine)
}
del machine["name"]
return ret
|
saltstack/salt
|
salt/cloud/clouds/virtualbox.py
|
list_nodes
|
python
|
def list_nodes(kwargs=None, call=None):
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
attributes = [
"id",
"image",
"size",
"state",
"private_ips",
"public_ips",
]
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), attributes, call,
)
|
This function returns a list of nodes available on this cloud provider, using the following fields:
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
No other fields should be returned in this function, and all of these fields should be returned, even if empty.
The private_ips and public_ips fields should always be of a list type, even if empty,
and the other fields should always be of a str type.
This function is normally called with the -Q option:
.. code-block:: bash
salt-cloud -Q
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/virtualbox.py#L271-L315
|
[
"def list_nodes_full(kwargs=None, call=None):\n \"\"\"\n All information available about all nodes should be returned in this function.\n The fields in the list_nodes() function should also be returned,\n even if they would not normally be provided by the cloud provider.\n\n This is because some functions both within Salt and 3rd party will break if an expected field is not present.\n This function is normally called with the -F option:\n\n\n .. code-block:: bash\n\n salt-cloud -F\n\n\n @param kwargs:\n @type kwargs:\n @param call:\n @type call:\n @return:\n @rtype:\n \"\"\"\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes_full function must be called '\n 'with -f or --function.'\n )\n\n machines = {}\n\n # TODO ask for the correct attributes e.g state and private_ips\n for machine in vb_list_machines():\n name = machine.get(\"name\")\n if name:\n machines[name] = treat_machine_dict(machine)\n del machine[\"name\"]\n\n return machines\n"
] |
# -*- coding: utf-8 -*-
'''
A salt cloud provider that lets you use virtualbox on your machine
and act as a cloud.
:depends: vboxapi
For now this will only clone existing VMs. It's best to create a template
from which we will clone.
Followed
https://docs.saltstack.com/en/latest/topics/cloud/cloud.html#non-libcloud-based-modules
to create this.
Dicts provided by salt:
__opts__ : contains the options used to run Salt Cloud,
as well as a set of configuration and environment variables
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
from salt.exceptions import SaltCloudSystemExit
import salt.config as config
# Import Third Party Libs
try:
import vboxapi # pylint: disable=unused-import
from salt.utils.virtualbox import (
vb_list_machines,
vb_clone_vm,
vb_machine_exists,
vb_destroy_machine,
vb_get_machine,
vb_stop_vm,
treat_machine_dict,
vb_start_vm,
vb_wait_for_network_address
)
HAS_VBOX = True
except ImportError:
HAS_VBOX = False
log = logging.getLogger(__name__)
# The name salt will identify the lib by
__virtualname__ = 'virtualbox'
#if no clone mode is specified in the virtualbox profile
#then default to 0 which was the old default value
DEFAULT_CLONE_MODE = 0
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_VBOX:
return False, 'The virtualbox driver cannot be loaded: \'vboxapi\' is not installed.'
if get_configured_provider() is False:
return False, 'The virtualbox driver cannot be loaded: \'virtualbox\' provider is not configured.'
# If the name of the driver used does not match the filename,
# then that name should be returned instead of True.
return __virtualname__
def get_configured_provider():
"""
Return the first configured instance.
"""
configured = config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
() # keys we need from the provider configuration
)
return configured
def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
"""
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info['clonemode'] in mode_map:
return mode_map[vm_info['clonemode']]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(','.join(mode_map.keys()))
)
def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires the event ``salt/cloud/vm_name/creating``, with the
payload containing the names of the VM, profile, and provider.
@param vm_info
.. code-block:: text
{
name: <str>
profile: <dict>
driver: <provider>:<profile>
clonefrom: <vm_name>
clonemode: <mode> (default: state, choices: state, child, all)
}
@type vm_info dict
@return dict of resulting vm. !!!Passwords can and should be included!!!
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_info['profile'] and config.is_profile_configured(
__opts__,
__active_provider_name__ or 'virtualbox',
vm_info['profile']
) is False:
return False
except AttributeError:
pass
vm_name = vm_info["name"]
deploy = config.get_cloud_config_value(
'deploy', vm_info, __opts__, search_global=False, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_info, __opts__, default=60
)
boot_timeout = config.get_cloud_config_value(
'boot_timeout', vm_info, __opts__, default=60 * 1000
)
power = config.get_cloud_config_value(
'power_on', vm_info, __opts__, default=False
)
key_filename = config.get_cloud_config_value(
'private_key', vm_info, __opts__, search_global=False, default=None
)
clone_mode = map_clonemode(vm_info)
wait_for_pattern = vm_info['waitforpattern'] if 'waitforpattern' in vm_info.keys() else None
interface_index = vm_info['interfaceindex'] if 'interfaceindex' in vm_info.keys() else 0
log.debug("Going to fire event: starting create")
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('creating', vm_info, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# to create the virtual machine.
request_kwargs = {
'name': vm_info['name'],
'clone_from': vm_info['clonefrom'],
'clone_mode': clone_mode
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('requesting', request_kwargs, list(request_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_result = vb_clone_vm(**request_kwargs)
# Booting and deploying if needed
if power:
vb_start_vm(vm_name, timeout=boot_timeout)
ips = vb_wait_for_network_address(wait_for_ip_timeout, machine_name=vm_name, wait_for_pattern=wait_for_pattern)
if ips:
ip = ips[interface_index]
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_info['key_filename'] = key_filename
vm_info['ssh_host'] = ip
res = __utils__['cloud.bootstrap'](vm_info, __opts__)
vm_result.update(res)
__utils__['cloud.fire_event'](
'event',
'created machine',
'salt/cloud/{0}/created'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('created', vm_result, list(vm_result)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Passwords should be included in this object!!
return vm_result
def list_nodes_full(kwargs=None, call=None):
"""
All information available about all nodes should be returned in this function.
The fields in the list_nodes() function should also be returned,
even if they would not normally be provided by the cloud provider.
This is because some functions both within Salt and 3rd party will break if an expected field is not present.
This function is normally called with the -F option:
.. code-block:: bash
salt-cloud -F
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
machines = {}
# TODO ask for the correct attributes e.g state and private_ips
for machine in vb_list_machines():
name = machine.get("name")
if name:
machines[name] = treat_machine_dict(machine)
del machine["name"]
return machines
def list_nodes_select(call=None):
"""
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), __opts__['query.selection'], call,
)
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if not vb_machine_exists(name):
return "{0} doesn't exist and can't be deleted".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vb_destroy_machine(name)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def start(name, call=None):
'''
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
'''
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Starting machine: %s", name)
vb_start_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def stop(name, call=None):
"""
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
"""
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Stopping machine: %s", name)
vb_stop_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def show_image(kwargs, call=None):
"""
Show the details of an image
"""
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_machine(name)
ret = {
machine["name"]: treat_machine_dict(machine)
}
del machine["name"]
return ret
|
saltstack/salt
|
salt/cloud/clouds/virtualbox.py
|
destroy
|
python
|
def destroy(name, call=None):
log.info("Attempting to delete instance %s", name)
if not vb_machine_exists(name):
return "{0} doesn't exist and can't be deleted".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vb_destroy_machine(name)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
|
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/virtualbox.py#L327-L368
|
[
"def vb_destroy_machine(name=None, timeout=10000):\n '''\n Attempts to get rid of a machine and all its files from the hypervisor\n @param name:\n @type name: str\n @param timeout int timeout in milliseconds\n '''\n vbox = vb_get_box()\n log.info('Destroying machine %s', name)\n machine = vbox.findMachine(name)\n files = machine.unregister(2)\n progress = machine.deleteConfig(files)\n progress.waitForCompletion(timeout)\n log.info('Finished destroying machine %s', name)\n",
"def vb_machine_exists(name):\n '''\n Checks in with the hypervisor to see if the machine with the given name is known\n @param name:\n @type name:\n @return:\n @rtype:\n '''\n try:\n vbox = vb_get_box()\n vbox.findMachine(name)\n return True\n except Exception as e:\n if isinstance(e.message, six.string_types):\n message = e.message\n elif hasattr(e, 'msg') and isinstance(getattr(e, 'msg'), six.string_types):\n message = getattr(e, 'msg')\n else:\n message = ''\n if 0 > message.find('Could not find a registered machine named'):\n log.error(message)\n\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
A salt cloud provider that lets you use virtualbox on your machine
and act as a cloud.
:depends: vboxapi
For now this will only clone existing VMs. It's best to create a template
from which we will clone.
Followed
https://docs.saltstack.com/en/latest/topics/cloud/cloud.html#non-libcloud-based-modules
to create this.
Dicts provided by salt:
__opts__ : contains the options used to run Salt Cloud,
as well as a set of configuration and environment variables
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
from salt.exceptions import SaltCloudSystemExit
import salt.config as config
# Import Third Party Libs
try:
import vboxapi # pylint: disable=unused-import
from salt.utils.virtualbox import (
vb_list_machines,
vb_clone_vm,
vb_machine_exists,
vb_destroy_machine,
vb_get_machine,
vb_stop_vm,
treat_machine_dict,
vb_start_vm,
vb_wait_for_network_address
)
HAS_VBOX = True
except ImportError:
HAS_VBOX = False
log = logging.getLogger(__name__)
# The name salt will identify the lib by
__virtualname__ = 'virtualbox'
#if no clone mode is specified in the virtualbox profile
#then default to 0 which was the old default value
DEFAULT_CLONE_MODE = 0
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_VBOX:
return False, 'The virtualbox driver cannot be loaded: \'vboxapi\' is not installed.'
if get_configured_provider() is False:
return False, 'The virtualbox driver cannot be loaded: \'virtualbox\' provider is not configured.'
# If the name of the driver used does not match the filename,
# then that name should be returned instead of True.
return __virtualname__
def get_configured_provider():
"""
Return the first configured instance.
"""
configured = config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
() # keys we need from the provider configuration
)
return configured
def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
"""
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info['clonemode'] in mode_map:
return mode_map[vm_info['clonemode']]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(','.join(mode_map.keys()))
)
def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires the event ``salt/cloud/vm_name/creating``, with the
payload containing the names of the VM, profile, and provider.
@param vm_info
.. code-block:: text
{
name: <str>
profile: <dict>
driver: <provider>:<profile>
clonefrom: <vm_name>
clonemode: <mode> (default: state, choices: state, child, all)
}
@type vm_info dict
@return dict of resulting vm. !!!Passwords can and should be included!!!
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_info['profile'] and config.is_profile_configured(
__opts__,
__active_provider_name__ or 'virtualbox',
vm_info['profile']
) is False:
return False
except AttributeError:
pass
vm_name = vm_info["name"]
deploy = config.get_cloud_config_value(
'deploy', vm_info, __opts__, search_global=False, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_info, __opts__, default=60
)
boot_timeout = config.get_cloud_config_value(
'boot_timeout', vm_info, __opts__, default=60 * 1000
)
power = config.get_cloud_config_value(
'power_on', vm_info, __opts__, default=False
)
key_filename = config.get_cloud_config_value(
'private_key', vm_info, __opts__, search_global=False, default=None
)
clone_mode = map_clonemode(vm_info)
wait_for_pattern = vm_info['waitforpattern'] if 'waitforpattern' in vm_info.keys() else None
interface_index = vm_info['interfaceindex'] if 'interfaceindex' in vm_info.keys() else 0
log.debug("Going to fire event: starting create")
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('creating', vm_info, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# to create the virtual machine.
request_kwargs = {
'name': vm_info['name'],
'clone_from': vm_info['clonefrom'],
'clone_mode': clone_mode
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('requesting', request_kwargs, list(request_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_result = vb_clone_vm(**request_kwargs)
# Booting and deploying if needed
if power:
vb_start_vm(vm_name, timeout=boot_timeout)
ips = vb_wait_for_network_address(wait_for_ip_timeout, machine_name=vm_name, wait_for_pattern=wait_for_pattern)
if ips:
ip = ips[interface_index]
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_info['key_filename'] = key_filename
vm_info['ssh_host'] = ip
res = __utils__['cloud.bootstrap'](vm_info, __opts__)
vm_result.update(res)
__utils__['cloud.fire_event'](
'event',
'created machine',
'salt/cloud/{0}/created'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('created', vm_result, list(vm_result)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Passwords should be included in this object!!
return vm_result
def list_nodes_full(kwargs=None, call=None):
"""
All information available about all nodes should be returned in this function.
The fields in the list_nodes() function should also be returned,
even if they would not normally be provided by the cloud provider.
This is because some functions both within Salt and 3rd party will break if an expected field is not present.
This function is normally called with the -F option:
.. code-block:: bash
salt-cloud -F
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
machines = {}
# TODO ask for the correct attributes e.g state and private_ips
for machine in vb_list_machines():
name = machine.get("name")
if name:
machines[name] = treat_machine_dict(machine)
del machine["name"]
return machines
def list_nodes(kwargs=None, call=None):
"""
This function returns a list of nodes available on this cloud provider, using the following fields:
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
No other fields should be returned in this function, and all of these fields should be returned, even if empty.
The private_ips and public_ips fields should always be of a list type, even if empty,
and the other fields should always be of a str type.
This function is normally called with the -Q option:
.. code-block:: bash
salt-cloud -Q
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
attributes = [
"id",
"image",
"size",
"state",
"private_ips",
"public_ips",
]
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), attributes, call,
)
def list_nodes_select(call=None):
"""
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), __opts__['query.selection'], call,
)
def start(name, call=None):
'''
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
'''
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Starting machine: %s", name)
vb_start_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def stop(name, call=None):
"""
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
"""
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Stopping machine: %s", name)
vb_stop_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def show_image(kwargs, call=None):
"""
Show the details of an image
"""
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_machine(name)
ret = {
machine["name"]: treat_machine_dict(machine)
}
del machine["name"]
return ret
|
saltstack/salt
|
salt/cloud/clouds/virtualbox.py
|
start
|
python
|
def start(name, call=None):
'''
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
'''
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Starting machine: %s", name)
vb_start_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
|
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/virtualbox.py#L371-L388
|
[
"def vb_start_vm(name=None, timeout=10000, **kwargs):\n '''\n Tells Virtualbox to start up a VM.\n Blocking function!\n\n @param name:\n @type name: str\n @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely\n @type timeout: int\n @return untreated dict of started VM\n '''\n # Time tracking\n start_time = time.time()\n timeout_in_seconds = timeout / 1000\n max_time = start_time + timeout_in_seconds\n\n vbox = vb_get_box()\n machine = vbox.findMachine(name)\n session = _virtualboxManager.getSessionObject(vbox)\n\n log.info('Starting machine %s in state %s', name, vb_machinestate_to_str(machine.state))\n try:\n # Keep trying to start a machine\n args = (machine, session)\n progress = wait_for(_start_machine, timeout=timeout_in_seconds, func_args=args)\n if not progress:\n progress = machine.launchVMProcess(session, '', '')\n\n # We already waited for stuff, don't push it\n time_left = max_time - time.time()\n progress.waitForCompletion(time_left * 1000)\n finally:\n _virtualboxManager.closeMachineSession(session)\n\n # The session state should best be unlocked otherwise subsequent calls might cause problems\n time_left = max_time - time.time()\n vb_wait_for_session_state(session, timeout=time_left)\n log.info('Started machine %s', name)\n\n return vb_xpcom_to_attribute_dict(machine, 'IMachine')\n",
"def vb_get_machine(name, **kwargs):\n '''\n Attempts to fetch a machine from Virtualbox and convert it to a dict\n\n @param name: The unique name of the machine\n @type name:\n @param kwargs: To be passed to vb_xpcom_to_attribute_dict\n @type kwargs:\n @return:\n @rtype: dict\n '''\n vbox = vb_get_box()\n machine = vbox.findMachine(name)\n return vb_xpcom_to_attribute_dict(machine, 'IMachine', **kwargs)\n",
"def treat_machine_dict(machine):\n '''\n Make machine presentable for outside world.\n\n !!!Modifies the input machine!!!\n\n @param machine:\n @type machine: dict\n @return: the modified input machine\n @rtype: dict\n '''\n machine.update({\n 'id': machine.get('id', ''),\n 'image': machine.get('image', ''),\n 'size': '{0} MB'.format(machine.get('memorySize', 0)),\n 'state': machine_get_machinestate_str(machine),\n 'private_ips': [],\n 'public_ips': [],\n })\n\n # Replaced keys\n if 'memorySize' in machine:\n del machine['memorySize']\n return machine\n"
] |
# -*- coding: utf-8 -*-
'''
A salt cloud provider that lets you use virtualbox on your machine
and act as a cloud.
:depends: vboxapi
For now this will only clone existing VMs. It's best to create a template
from which we will clone.
Followed
https://docs.saltstack.com/en/latest/topics/cloud/cloud.html#non-libcloud-based-modules
to create this.
Dicts provided by salt:
__opts__ : contains the options used to run Salt Cloud,
as well as a set of configuration and environment variables
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
from salt.exceptions import SaltCloudSystemExit
import salt.config as config
# Import Third Party Libs
try:
import vboxapi # pylint: disable=unused-import
from salt.utils.virtualbox import (
vb_list_machines,
vb_clone_vm,
vb_machine_exists,
vb_destroy_machine,
vb_get_machine,
vb_stop_vm,
treat_machine_dict,
vb_start_vm,
vb_wait_for_network_address
)
HAS_VBOX = True
except ImportError:
HAS_VBOX = False
log = logging.getLogger(__name__)
# The name salt will identify the lib by
__virtualname__ = 'virtualbox'
#if no clone mode is specified in the virtualbox profile
#then default to 0 which was the old default value
DEFAULT_CLONE_MODE = 0
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_VBOX:
return False, 'The virtualbox driver cannot be loaded: \'vboxapi\' is not installed.'
if get_configured_provider() is False:
return False, 'The virtualbox driver cannot be loaded: \'virtualbox\' provider is not configured.'
# If the name of the driver used does not match the filename,
# then that name should be returned instead of True.
return __virtualname__
def get_configured_provider():
"""
Return the first configured instance.
"""
configured = config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
() # keys we need from the provider configuration
)
return configured
def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
"""
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info['clonemode'] in mode_map:
return mode_map[vm_info['clonemode']]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(','.join(mode_map.keys()))
)
def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires the event ``salt/cloud/vm_name/creating``, with the
payload containing the names of the VM, profile, and provider.
@param vm_info
.. code-block:: text
{
name: <str>
profile: <dict>
driver: <provider>:<profile>
clonefrom: <vm_name>
clonemode: <mode> (default: state, choices: state, child, all)
}
@type vm_info dict
@return dict of resulting vm. !!!Passwords can and should be included!!!
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_info['profile'] and config.is_profile_configured(
__opts__,
__active_provider_name__ or 'virtualbox',
vm_info['profile']
) is False:
return False
except AttributeError:
pass
vm_name = vm_info["name"]
deploy = config.get_cloud_config_value(
'deploy', vm_info, __opts__, search_global=False, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_info, __opts__, default=60
)
boot_timeout = config.get_cloud_config_value(
'boot_timeout', vm_info, __opts__, default=60 * 1000
)
power = config.get_cloud_config_value(
'power_on', vm_info, __opts__, default=False
)
key_filename = config.get_cloud_config_value(
'private_key', vm_info, __opts__, search_global=False, default=None
)
clone_mode = map_clonemode(vm_info)
wait_for_pattern = vm_info['waitforpattern'] if 'waitforpattern' in vm_info.keys() else None
interface_index = vm_info['interfaceindex'] if 'interfaceindex' in vm_info.keys() else 0
log.debug("Going to fire event: starting create")
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('creating', vm_info, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# to create the virtual machine.
request_kwargs = {
'name': vm_info['name'],
'clone_from': vm_info['clonefrom'],
'clone_mode': clone_mode
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('requesting', request_kwargs, list(request_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_result = vb_clone_vm(**request_kwargs)
# Booting and deploying if needed
if power:
vb_start_vm(vm_name, timeout=boot_timeout)
ips = vb_wait_for_network_address(wait_for_ip_timeout, machine_name=vm_name, wait_for_pattern=wait_for_pattern)
if ips:
ip = ips[interface_index]
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_info['key_filename'] = key_filename
vm_info['ssh_host'] = ip
res = __utils__['cloud.bootstrap'](vm_info, __opts__)
vm_result.update(res)
__utils__['cloud.fire_event'](
'event',
'created machine',
'salt/cloud/{0}/created'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('created', vm_result, list(vm_result)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Passwords should be included in this object!!
return vm_result
def list_nodes_full(kwargs=None, call=None):
"""
All information available about all nodes should be returned in this function.
The fields in the list_nodes() function should also be returned,
even if they would not normally be provided by the cloud provider.
This is because some functions both within Salt and 3rd party will break if an expected field is not present.
This function is normally called with the -F option:
.. code-block:: bash
salt-cloud -F
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
machines = {}
# TODO ask for the correct attributes e.g state and private_ips
for machine in vb_list_machines():
name = machine.get("name")
if name:
machines[name] = treat_machine_dict(machine)
del machine["name"]
return machines
def list_nodes(kwargs=None, call=None):
"""
This function returns a list of nodes available on this cloud provider, using the following fields:
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
No other fields should be returned in this function, and all of these fields should be returned, even if empty.
The private_ips and public_ips fields should always be of a list type, even if empty,
and the other fields should always be of a str type.
This function is normally called with the -Q option:
.. code-block:: bash
salt-cloud -Q
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
attributes = [
"id",
"image",
"size",
"state",
"private_ips",
"public_ips",
]
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), attributes, call,
)
def list_nodes_select(call=None):
"""
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), __opts__['query.selection'], call,
)
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if not vb_machine_exists(name):
return "{0} doesn't exist and can't be deleted".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vb_destroy_machine(name)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def stop(name, call=None):
"""
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
"""
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Stopping machine: %s", name)
vb_stop_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def show_image(kwargs, call=None):
"""
Show the details of an image
"""
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_machine(name)
ret = {
machine["name"]: treat_machine_dict(machine)
}
del machine["name"]
return ret
|
saltstack/salt
|
salt/cloud/clouds/virtualbox.py
|
stop
|
python
|
def stop(name, call=None):
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Stopping machine: %s", name)
vb_stop_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
|
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/virtualbox.py#L391-L408
|
[
"def vb_stop_vm(name=None, timeout=10000, **kwargs):\n '''\n Tells Virtualbox to stop a VM.\n This is a blocking function!\n\n @param name:\n @type name: str\n @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely\n @type timeout: int\n @return untreated dict of stopped VM\n '''\n vbox = vb_get_box()\n machine = vbox.findMachine(name)\n log.info('Stopping machine %s', name)\n session = _virtualboxManager.openMachineSession(machine)\n try:\n console = session.console\n progress = console.powerDown()\n progress.waitForCompletion(timeout)\n finally:\n _virtualboxManager.closeMachineSession(session)\n vb_wait_for_session_state(session)\n log.info('Stopped machine %s is now %s', name, vb_machinestate_to_str(machine.state))\n return vb_xpcom_to_attribute_dict(machine, 'IMachine')\n",
"def vb_get_machine(name, **kwargs):\n '''\n Attempts to fetch a machine from Virtualbox and convert it to a dict\n\n @param name: The unique name of the machine\n @type name:\n @param kwargs: To be passed to vb_xpcom_to_attribute_dict\n @type kwargs:\n @return:\n @rtype: dict\n '''\n vbox = vb_get_box()\n machine = vbox.findMachine(name)\n return vb_xpcom_to_attribute_dict(machine, 'IMachine', **kwargs)\n",
"def treat_machine_dict(machine):\n '''\n Make machine presentable for outside world.\n\n !!!Modifies the input machine!!!\n\n @param machine:\n @type machine: dict\n @return: the modified input machine\n @rtype: dict\n '''\n machine.update({\n 'id': machine.get('id', ''),\n 'image': machine.get('image', ''),\n 'size': '{0} MB'.format(machine.get('memorySize', 0)),\n 'state': machine_get_machinestate_str(machine),\n 'private_ips': [],\n 'public_ips': [],\n })\n\n # Replaced keys\n if 'memorySize' in machine:\n del machine['memorySize']\n return machine\n"
] |
# -*- coding: utf-8 -*-
'''
A salt cloud provider that lets you use virtualbox on your machine
and act as a cloud.
:depends: vboxapi
For now this will only clone existing VMs. It's best to create a template
from which we will clone.
Followed
https://docs.saltstack.com/en/latest/topics/cloud/cloud.html#non-libcloud-based-modules
to create this.
Dicts provided by salt:
__opts__ : contains the options used to run Salt Cloud,
as well as a set of configuration and environment variables
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
from salt.exceptions import SaltCloudSystemExit
import salt.config as config
# Import Third Party Libs
try:
import vboxapi # pylint: disable=unused-import
from salt.utils.virtualbox import (
vb_list_machines,
vb_clone_vm,
vb_machine_exists,
vb_destroy_machine,
vb_get_machine,
vb_stop_vm,
treat_machine_dict,
vb_start_vm,
vb_wait_for_network_address
)
HAS_VBOX = True
except ImportError:
HAS_VBOX = False
log = logging.getLogger(__name__)
# The name salt will identify the lib by
__virtualname__ = 'virtualbox'
#if no clone mode is specified in the virtualbox profile
#then default to 0 which was the old default value
DEFAULT_CLONE_MODE = 0
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_VBOX:
return False, 'The virtualbox driver cannot be loaded: \'vboxapi\' is not installed.'
if get_configured_provider() is False:
return False, 'The virtualbox driver cannot be loaded: \'virtualbox\' provider is not configured.'
# If the name of the driver used does not match the filename,
# then that name should be returned instead of True.
return __virtualname__
def get_configured_provider():
"""
Return the first configured instance.
"""
configured = config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
() # keys we need from the provider configuration
)
return configured
def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
"""
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info['clonemode'] in mode_map:
return mode_map[vm_info['clonemode']]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(','.join(mode_map.keys()))
)
def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires the event ``salt/cloud/vm_name/creating``, with the
payload containing the names of the VM, profile, and provider.
@param vm_info
.. code-block:: text
{
name: <str>
profile: <dict>
driver: <provider>:<profile>
clonefrom: <vm_name>
clonemode: <mode> (default: state, choices: state, child, all)
}
@type vm_info dict
@return dict of resulting vm. !!!Passwords can and should be included!!!
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_info['profile'] and config.is_profile_configured(
__opts__,
__active_provider_name__ or 'virtualbox',
vm_info['profile']
) is False:
return False
except AttributeError:
pass
vm_name = vm_info["name"]
deploy = config.get_cloud_config_value(
'deploy', vm_info, __opts__, search_global=False, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_info, __opts__, default=60
)
boot_timeout = config.get_cloud_config_value(
'boot_timeout', vm_info, __opts__, default=60 * 1000
)
power = config.get_cloud_config_value(
'power_on', vm_info, __opts__, default=False
)
key_filename = config.get_cloud_config_value(
'private_key', vm_info, __opts__, search_global=False, default=None
)
clone_mode = map_clonemode(vm_info)
wait_for_pattern = vm_info['waitforpattern'] if 'waitforpattern' in vm_info.keys() else None
interface_index = vm_info['interfaceindex'] if 'interfaceindex' in vm_info.keys() else 0
log.debug("Going to fire event: starting create")
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('creating', vm_info, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# to create the virtual machine.
request_kwargs = {
'name': vm_info['name'],
'clone_from': vm_info['clonefrom'],
'clone_mode': clone_mode
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('requesting', request_kwargs, list(request_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_result = vb_clone_vm(**request_kwargs)
# Booting and deploying if needed
if power:
vb_start_vm(vm_name, timeout=boot_timeout)
ips = vb_wait_for_network_address(wait_for_ip_timeout, machine_name=vm_name, wait_for_pattern=wait_for_pattern)
if ips:
ip = ips[interface_index]
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_info['key_filename'] = key_filename
vm_info['ssh_host'] = ip
res = __utils__['cloud.bootstrap'](vm_info, __opts__)
vm_result.update(res)
__utils__['cloud.fire_event'](
'event',
'created machine',
'salt/cloud/{0}/created'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('created', vm_result, list(vm_result)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Passwords should be included in this object!!
return vm_result
def list_nodes_full(kwargs=None, call=None):
"""
All information available about all nodes should be returned in this function.
The fields in the list_nodes() function should also be returned,
even if they would not normally be provided by the cloud provider.
This is because some functions both within Salt and 3rd party will break if an expected field is not present.
This function is normally called with the -F option:
.. code-block:: bash
salt-cloud -F
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
machines = {}
# TODO ask for the correct attributes e.g state and private_ips
for machine in vb_list_machines():
name = machine.get("name")
if name:
machines[name] = treat_machine_dict(machine)
del machine["name"]
return machines
def list_nodes(kwargs=None, call=None):
"""
This function returns a list of nodes available on this cloud provider, using the following fields:
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
No other fields should be returned in this function, and all of these fields should be returned, even if empty.
The private_ips and public_ips fields should always be of a list type, even if empty,
and the other fields should always be of a str type.
This function is normally called with the -Q option:
.. code-block:: bash
salt-cloud -Q
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
attributes = [
"id",
"image",
"size",
"state",
"private_ips",
"public_ips",
]
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), attributes, call,
)
def list_nodes_select(call=None):
"""
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), __opts__['query.selection'], call,
)
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if not vb_machine_exists(name):
return "{0} doesn't exist and can't be deleted".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vb_destroy_machine(name)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def start(name, call=None):
'''
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
'''
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Starting machine: %s", name)
vb_start_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def show_image(kwargs, call=None):
"""
Show the details of an image
"""
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_machine(name)
ret = {
machine["name"]: treat_machine_dict(machine)
}
del machine["name"]
return ret
|
saltstack/salt
|
salt/cloud/clouds/virtualbox.py
|
show_image
|
python
|
def show_image(kwargs, call=None):
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_machine(name)
ret = {
machine["name"]: treat_machine_dict(machine)
}
del machine["name"]
return ret
|
Show the details of an image
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/virtualbox.py#L411-L428
|
[
"def vb_get_machine(name, **kwargs):\n '''\n Attempts to fetch a machine from Virtualbox and convert it to a dict\n\n @param name: The unique name of the machine\n @type name:\n @param kwargs: To be passed to vb_xpcom_to_attribute_dict\n @type kwargs:\n @return:\n @rtype: dict\n '''\n vbox = vb_get_box()\n machine = vbox.findMachine(name)\n return vb_xpcom_to_attribute_dict(machine, 'IMachine', **kwargs)\n",
"def treat_machine_dict(machine):\n '''\n Make machine presentable for outside world.\n\n !!!Modifies the input machine!!!\n\n @param machine:\n @type machine: dict\n @return: the modified input machine\n @rtype: dict\n '''\n machine.update({\n 'id': machine.get('id', ''),\n 'image': machine.get('image', ''),\n 'size': '{0} MB'.format(machine.get('memorySize', 0)),\n 'state': machine_get_machinestate_str(machine),\n 'private_ips': [],\n 'public_ips': [],\n })\n\n # Replaced keys\n if 'memorySize' in machine:\n del machine['memorySize']\n return machine\n"
] |
# -*- coding: utf-8 -*-
'''
A salt cloud provider that lets you use virtualbox on your machine
and act as a cloud.
:depends: vboxapi
For now this will only clone existing VMs. It's best to create a template
from which we will clone.
Followed
https://docs.saltstack.com/en/latest/topics/cloud/cloud.html#non-libcloud-based-modules
to create this.
Dicts provided by salt:
__opts__ : contains the options used to run Salt Cloud,
as well as a set of configuration and environment variables
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
from salt.exceptions import SaltCloudSystemExit
import salt.config as config
# Import Third Party Libs
try:
import vboxapi # pylint: disable=unused-import
from salt.utils.virtualbox import (
vb_list_machines,
vb_clone_vm,
vb_machine_exists,
vb_destroy_machine,
vb_get_machine,
vb_stop_vm,
treat_machine_dict,
vb_start_vm,
vb_wait_for_network_address
)
HAS_VBOX = True
except ImportError:
HAS_VBOX = False
log = logging.getLogger(__name__)
# The name salt will identify the lib by
__virtualname__ = 'virtualbox'
#if no clone mode is specified in the virtualbox profile
#then default to 0 which was the old default value
DEFAULT_CLONE_MODE = 0
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_VBOX:
return False, 'The virtualbox driver cannot be loaded: \'vboxapi\' is not installed.'
if get_configured_provider() is False:
return False, 'The virtualbox driver cannot be loaded: \'virtualbox\' provider is not configured.'
# If the name of the driver used does not match the filename,
# then that name should be returned instead of True.
return __virtualname__
def get_configured_provider():
"""
Return the first configured instance.
"""
configured = config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
() # keys we need from the provider configuration
)
return configured
def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
"""
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info['clonemode'] in mode_map:
return mode_map[vm_info['clonemode']]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(','.join(mode_map.keys()))
)
def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires the event ``salt/cloud/vm_name/creating``, with the
payload containing the names of the VM, profile, and provider.
@param vm_info
.. code-block:: text
{
name: <str>
profile: <dict>
driver: <provider>:<profile>
clonefrom: <vm_name>
clonemode: <mode> (default: state, choices: state, child, all)
}
@type vm_info dict
@return dict of resulting vm. !!!Passwords can and should be included!!!
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_info['profile'] and config.is_profile_configured(
__opts__,
__active_provider_name__ or 'virtualbox',
vm_info['profile']
) is False:
return False
except AttributeError:
pass
vm_name = vm_info["name"]
deploy = config.get_cloud_config_value(
'deploy', vm_info, __opts__, search_global=False, default=True
)
wait_for_ip_timeout = config.get_cloud_config_value(
'wait_for_ip_timeout', vm_info, __opts__, default=60
)
boot_timeout = config.get_cloud_config_value(
'boot_timeout', vm_info, __opts__, default=60 * 1000
)
power = config.get_cloud_config_value(
'power_on', vm_info, __opts__, default=False
)
key_filename = config.get_cloud_config_value(
'private_key', vm_info, __opts__, search_global=False, default=None
)
clone_mode = map_clonemode(vm_info)
wait_for_pattern = vm_info['waitforpattern'] if 'waitforpattern' in vm_info.keys() else None
interface_index = vm_info['interfaceindex'] if 'interfaceindex' in vm_info.keys() else 0
log.debug("Going to fire event: starting create")
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('creating', vm_info, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# to create the virtual machine.
request_kwargs = {
'name': vm_info['name'],
'clone_from': vm_info['clonefrom'],
'clone_mode': clone_mode
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('requesting', request_kwargs, list(request_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vm_result = vb_clone_vm(**request_kwargs)
# Booting and deploying if needed
if power:
vb_start_vm(vm_name, timeout=boot_timeout)
ips = vb_wait_for_network_address(wait_for_ip_timeout, machine_name=vm_name, wait_for_pattern=wait_for_pattern)
if ips:
ip = ips[interface_index]
log.info("[ %s ] IPv4 is: %s", vm_name, ip)
# ssh or smb using ip and install salt only if deploy is True
if deploy:
vm_info['key_filename'] = key_filename
vm_info['ssh_host'] = ip
res = __utils__['cloud.bootstrap'](vm_info, __opts__)
vm_result.update(res)
__utils__['cloud.fire_event'](
'event',
'created machine',
'salt/cloud/{0}/created'.format(vm_info['name']),
args=__utils__['cloud.filter_event']('created', vm_result, list(vm_result)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Passwords should be included in this object!!
return vm_result
def list_nodes_full(kwargs=None, call=None):
"""
All information available about all nodes should be returned in this function.
The fields in the list_nodes() function should also be returned,
even if they would not normally be provided by the cloud provider.
This is because some functions both within Salt and 3rd party will break if an expected field is not present.
This function is normally called with the -F option:
.. code-block:: bash
salt-cloud -F
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
machines = {}
# TODO ask for the correct attributes e.g state and private_ips
for machine in vb_list_machines():
name = machine.get("name")
if name:
machines[name] = treat_machine_dict(machine)
del machine["name"]
return machines
def list_nodes(kwargs=None, call=None):
"""
This function returns a list of nodes available on this cloud provider, using the following fields:
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
No other fields should be returned in this function, and all of these fields should be returned, even if empty.
The private_ips and public_ips fields should always be of a list type, even if empty,
and the other fields should always be of a str type.
This function is normally called with the -Q option:
.. code-block:: bash
salt-cloud -Q
@param kwargs:
@type kwargs:
@param call:
@type call:
@return:
@rtype:
"""
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
attributes = [
"id",
"image",
"size",
"state",
"private_ips",
"public_ips",
]
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), attributes, call,
)
def list_nodes_select(call=None):
"""
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__['cloud.list_nodes_select'](
list_nodes_full('function'), __opts__['query.selection'], call,
)
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if not vb_machine_exists(name):
return "{0} doesn't exist and can't be deleted".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
vb_destroy_machine(name)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def start(name, call=None):
'''
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
'''
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Starting machine: %s", name)
vb_start_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
def stop(name, call=None):
"""
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
"""
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Stopping machine: %s", name)
vb_stop_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine)
|
saltstack/salt
|
salt/states/cryptdev.py
|
mapped
|
python
|
def mapped(name,
device,
keyfile=None,
opts=None,
config='/etc/crypttab',
persist=True,
immediate=False,
match_on='name'):
'''
Verify that a device is mapped
name
The name under which the device is to be mapped
device
The device name, typically the device node, such as ``/dev/sdb1``
or ``UUID=066e0200-2867-4ebe-b9e6-f30026ca2314``.
keyfile
Either ``None`` if the password is to be entered manually on boot, or
an absolute path to a keyfile. If the password is to be asked
interactively, the mapping cannot be performed with ``immediate=True``.
opts
A list object of options or a comma delimited list
config
Set an alternative location for the crypttab, if the map is persistent,
Default is ``/etc/crypttab``
persist
Set if the map should be saved in the crypttab, Default is ``True``
immediate
Set if the device mapping should be executed immediately. Requires that
the keyfile not be ``None``, because the password cannot be asked
interactively. Note that options are not passed through on the initial
mapping. Default is ``False``.
match_on
A name or list of crypttab properties on which this state should be applied.
Default is ``name``, meaning that the line is matched only by the name
parameter. If the desired configuration requires two devices mapped to
the same name, supply a list of parameters to match on.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# If neither option is set, we've been asked to do nothing.
if not immediate and not persist:
ret['result'] = False
ret['comment'] = 'Either persist or immediate must be set, otherwise this state does nothing'
return ret
if immediate and (keyfile is None or keyfile == 'none' or keyfile == '-'):
ret['result'] = False
ret['changes']['cryptsetup'] = 'Device cannot be mapped immediately without a keyfile'
elif immediate:
# Get the active crypt mounts. If ours is listed already, no action is necessary.
active = __salt__['cryptdev.active']()
if name not in active.keys():
# Open the map using cryptsetup. This does not pass any options.
if opts:
log.warning('Ignore cryptdev configuration when mapping immediately')
if __opts__['test']:
ret['result'] = None
ret['commment'] = 'Device would be mapped immediately'
else:
cryptsetup_result = __salt__['cryptdev.open'](name, device, keyfile)
if cryptsetup_result:
ret['changes']['cryptsetup'] = 'Device mapped using cryptsetup'
else:
ret['changes']['cryptsetup'] = 'Device failed to map using cryptsetup'
ret['result'] = False
if persist and not __opts__['test']:
crypttab_result = __salt__['cryptdev.set_crypttab'](name,
device,
password=keyfile,
options=opts,
config=config,
match_on=match_on)
if crypttab_result:
if crypttab_result == 'new':
ret['changes']['crypttab'] = 'Entry added in {0}'.format(config)
if crypttab_result == 'change':
ret['changes']['crypttab'] = 'Existing entry in {0} changed'.format(config)
else:
ret['changes']['crypttab'] = 'Unable to set entry in {0}'.format(config)
ret['result'] = False
return ret
|
Verify that a device is mapped
name
The name under which the device is to be mapped
device
The device name, typically the device node, such as ``/dev/sdb1``
or ``UUID=066e0200-2867-4ebe-b9e6-f30026ca2314``.
keyfile
Either ``None`` if the password is to be entered manually on boot, or
an absolute path to a keyfile. If the password is to be asked
interactively, the mapping cannot be performed with ``immediate=True``.
opts
A list object of options or a comma delimited list
config
Set an alternative location for the crypttab, if the map is persistent,
Default is ``/etc/crypttab``
persist
Set if the map should be saved in the crypttab, Default is ``True``
immediate
Set if the device mapping should be executed immediately. Requires that
the keyfile not be ``None``, because the password cannot be asked
interactively. Note that options are not passed through on the initial
mapping. Default is ``False``.
match_on
A name or list of crypttab properties on which this state should be applied.
Default is ``name``, meaning that the line is matched only by the name
parameter. If the desired configuration requires two devices mapped to
the same name, supply a list of parameters to match on.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cryptdev.py#L37-L134
| null |
# -*- coding: utf-8 -*-
'''
Opening of Encrypted Devices
=======================
Ensure that an encrypted device is mapped with the `mapped` function:
.. code-block:: yaml
mappedname:
cryptdev.mapped:
- device: /dev/sdb1
- keyfile: /etc/keyfile.key
- opts:
- size=256
swap:
crypted.mapped:
- device: /dev/sdx4
- keyfile: /dev/urandom
- opts: swap,cipher=aes-cbc-essiv:sha256,size=256
mappedbyuuid:
crypted.mapped:
- device: UUID=066e0200-2867-4ebe-b9e6-f30026ca2314
- keyfile: /etc/keyfile.key
- config: /etc/alternate-crypttab
.. versionadded:: 2018.3.0
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
log = logging.getLogger(__name__)
def unmapped(name,
config='/etc/crypttab',
persist=True,
immediate=False):
'''
Ensure that a device is unmapped
name
The name to ensure is not mapped
config
Set an alternative location for the crypttab, if the map is persistent,
Default is ``/etc/crypttab``
persist
Set if the map should be removed from the crypttab. Default is ``True``
immediate
Set if the device should be unmapped immediately. Default is ``False``.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if immediate:
# Get the active crypt mounts. If ours is not listed already, no action is necessary.
active = __salt__['cryptdev.active']()
if name in active.keys():
# Close the map using cryptsetup.
if __opts__['test']:
ret['result'] = None
ret['commment'] = 'Device would be unmapped immediately'
else:
cryptsetup_result = __salt__['cryptdev.close'](name)
if cryptsetup_result:
ret['changes']['cryptsetup'] = 'Device unmapped using cryptsetup'
else:
ret['changes']['cryptsetup'] = 'Device failed to unmap using cryptsetup'
ret['result'] = False
if persist and not __opts__['test']:
crypttab_result = __salt__['cryptdev.rm_crypttab'](name, config=config)
if crypttab_result:
if crypttab_result == 'change':
ret['changes']['crypttab'] = 'Entry removed from {0}'.format(config)
else:
ret['changes']['crypttab'] = 'Unable to remove entry in {0}'.format(config)
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/cryptdev.py
|
unmapped
|
python
|
def unmapped(name,
config='/etc/crypttab',
persist=True,
immediate=False):
'''
Ensure that a device is unmapped
name
The name to ensure is not mapped
config
Set an alternative location for the crypttab, if the map is persistent,
Default is ``/etc/crypttab``
persist
Set if the map should be removed from the crypttab. Default is ``True``
immediate
Set if the device should be unmapped immediately. Default is ``False``.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if immediate:
# Get the active crypt mounts. If ours is not listed already, no action is necessary.
active = __salt__['cryptdev.active']()
if name in active.keys():
# Close the map using cryptsetup.
if __opts__['test']:
ret['result'] = None
ret['commment'] = 'Device would be unmapped immediately'
else:
cryptsetup_result = __salt__['cryptdev.close'](name)
if cryptsetup_result:
ret['changes']['cryptsetup'] = 'Device unmapped using cryptsetup'
else:
ret['changes']['cryptsetup'] = 'Device failed to unmap using cryptsetup'
ret['result'] = False
if persist and not __opts__['test']:
crypttab_result = __salt__['cryptdev.rm_crypttab'](name, config=config)
if crypttab_result:
if crypttab_result == 'change':
ret['changes']['crypttab'] = 'Entry removed from {0}'.format(config)
else:
ret['changes']['crypttab'] = 'Unable to remove entry in {0}'.format(config)
ret['result'] = False
return ret
|
Ensure that a device is unmapped
name
The name to ensure is not mapped
config
Set an alternative location for the crypttab, if the map is persistent,
Default is ``/etc/crypttab``
persist
Set if the map should be removed from the crypttab. Default is ``True``
immediate
Set if the device should be unmapped immediately. Default is ``False``.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cryptdev.py#L137-L188
| null |
# -*- coding: utf-8 -*-
'''
Opening of Encrypted Devices
=======================
Ensure that an encrypted device is mapped with the `mapped` function:
.. code-block:: yaml
mappedname:
cryptdev.mapped:
- device: /dev/sdb1
- keyfile: /etc/keyfile.key
- opts:
- size=256
swap:
crypted.mapped:
- device: /dev/sdx4
- keyfile: /dev/urandom
- opts: swap,cipher=aes-cbc-essiv:sha256,size=256
mappedbyuuid:
crypted.mapped:
- device: UUID=066e0200-2867-4ebe-b9e6-f30026ca2314
- keyfile: /etc/keyfile.key
- config: /etc/alternate-crypttab
.. versionadded:: 2018.3.0
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
log = logging.getLogger(__name__)
def mapped(name,
device,
keyfile=None,
opts=None,
config='/etc/crypttab',
persist=True,
immediate=False,
match_on='name'):
'''
Verify that a device is mapped
name
The name under which the device is to be mapped
device
The device name, typically the device node, such as ``/dev/sdb1``
or ``UUID=066e0200-2867-4ebe-b9e6-f30026ca2314``.
keyfile
Either ``None`` if the password is to be entered manually on boot, or
an absolute path to a keyfile. If the password is to be asked
interactively, the mapping cannot be performed with ``immediate=True``.
opts
A list object of options or a comma delimited list
config
Set an alternative location for the crypttab, if the map is persistent,
Default is ``/etc/crypttab``
persist
Set if the map should be saved in the crypttab, Default is ``True``
immediate
Set if the device mapping should be executed immediately. Requires that
the keyfile not be ``None``, because the password cannot be asked
interactively. Note that options are not passed through on the initial
mapping. Default is ``False``.
match_on
A name or list of crypttab properties on which this state should be applied.
Default is ``name``, meaning that the line is matched only by the name
parameter. If the desired configuration requires two devices mapped to
the same name, supply a list of parameters to match on.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# If neither option is set, we've been asked to do nothing.
if not immediate and not persist:
ret['result'] = False
ret['comment'] = 'Either persist or immediate must be set, otherwise this state does nothing'
return ret
if immediate and (keyfile is None or keyfile == 'none' or keyfile == '-'):
ret['result'] = False
ret['changes']['cryptsetup'] = 'Device cannot be mapped immediately without a keyfile'
elif immediate:
# Get the active crypt mounts. If ours is listed already, no action is necessary.
active = __salt__['cryptdev.active']()
if name not in active.keys():
# Open the map using cryptsetup. This does not pass any options.
if opts:
log.warning('Ignore cryptdev configuration when mapping immediately')
if __opts__['test']:
ret['result'] = None
ret['commment'] = 'Device would be mapped immediately'
else:
cryptsetup_result = __salt__['cryptdev.open'](name, device, keyfile)
if cryptsetup_result:
ret['changes']['cryptsetup'] = 'Device mapped using cryptsetup'
else:
ret['changes']['cryptsetup'] = 'Device failed to map using cryptsetup'
ret['result'] = False
if persist and not __opts__['test']:
crypttab_result = __salt__['cryptdev.set_crypttab'](name,
device,
password=keyfile,
options=opts,
config=config,
match_on=match_on)
if crypttab_result:
if crypttab_result == 'new':
ret['changes']['crypttab'] = 'Entry added in {0}'.format(config)
if crypttab_result == 'change':
ret['changes']['crypttab'] = 'Existing entry in {0} changed'.format(config)
else:
ret['changes']['crypttab'] = 'Unable to set entry in {0}'.format(config)
ret['result'] = False
return ret
|
saltstack/salt
|
salt/runners/pillar.py
|
show_top
|
python
|
def show_top(minion=None, saltenv='base'):
'''
Returns the compiled top data for pillar for a specific minion. If no
minion is specified, we use the first minion we find.
CLI Example:
.. code-block:: bash
salt-run pillar.show_top
'''
id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__)
if not grains and minion == __opts__['id']:
grains = salt.loader.grains(__opts__)
pillar = salt.pillar.Pillar(
__opts__,
grains,
id_,
saltenv)
top, errors = pillar.get_top()
if errors:
__jid_event__.fire_event({'data': errors, 'outputter': 'nested'}, 'progress')
return errors
# needed because pillar compilation clobbers grains etc via lazyLoader
# this resets the masterminion back to known state
__salt__['salt.cmd']('sys.reload_modules')
return top
|
Returns the compiled top data for pillar for a specific minion. If no
minion is specified, we use the first minion we find.
CLI Example:
.. code-block:: bash
salt-run pillar.show_top
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/pillar.py#L13-L43
|
[
"def get_minion_data(minion, opts):\n '''\n Get the grains/pillar for a specific minion. If minion is None, it\n will return the grains/pillar for the first minion it finds.\n\n Return value is a tuple of the minion ID, grains, and pillar\n '''\n grains = None\n pillar = None\n if opts.get('minion_data_cache', False):\n cache = salt.cache.factory(opts)\n if minion is None:\n for id_ in cache.list('minions'):\n data = cache.fetch('minions/{0}'.format(id_), 'data')\n if data is None:\n continue\n else:\n data = cache.fetch('minions/{0}'.format(minion), 'data')\n if data is not None:\n grains = data.get('grains', None)\n pillar = data.get('pillar', None)\n return minion if minion else None, grains, pillar\n",
"def get_top(self):\n '''\n Returns the high data derived from the top file\n '''\n tops, errors = self.get_tops()\n try:\n merged_tops = self.merge_tops(tops)\n except TypeError as err:\n merged_tops = OrderedDict()\n errors.append('Error encountered while rendering pillar top file.')\n return merged_tops, errors\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to interact with the pillar compiler on the master
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.pillar
import salt.loader
import salt.utils.minions
def show_pillar(minion='*', **kwargs):
'''
Returns the compiled pillar either of a specific minion
or just the global available pillars. This function assumes
that no minion has the id ``*``.
Function also accepts pillarenv as attribute in order to limit to a specific pillar branch of git
CLI Example:
shows minion specific pillar:
.. code-block:: bash
salt-run pillar.show_pillar 'www.example.com'
shows global pillar:
.. code-block:: bash
salt-run pillar.show_pillar
shows global pillar for 'dev' pillar environment:
(note that not specifying pillarenv will merge all pillar environments
using the master config option pillar_source_merging_strategy.)
.. code-block:: bash
salt-run pillar.show_pillar 'pillarenv=dev'
shows global pillar for 'dev' pillar environment and specific pillarenv = dev:
.. code-block:: bash
salt-run pillar.show_pillar 'saltenv=dev' 'pillarenv=dev'
API Example:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
runner = salt.runner.RunnerClient(opts)
pillar = runner.cmd('pillar.show_pillar', [])
print(pillar)
'''
pillarenv = None
saltenv = 'base'
id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__)
if not grains and minion == __opts__['id']:
grains = salt.loader.grains(__opts__)
if grains is None:
grains = {'fqdn': minion}
for key in kwargs:
if key == 'saltenv':
saltenv = kwargs[key]
elif key == 'pillarenv':
# pillarenv overridden on CLI
pillarenv = kwargs[key]
else:
grains[key] = kwargs[key]
pillar = salt.pillar.Pillar(
__opts__,
grains,
id_,
saltenv,
pillarenv=pillarenv)
compiled_pillar = pillar.compile_pillar()
# needed because pillar compilation clobbers grains etc via lazyLoader
# this resets the masterminion back to known state
__salt__['salt.cmd']('sys.reload_modules')
return compiled_pillar
|
saltstack/salt
|
salt/runners/pillar.py
|
show_pillar
|
python
|
def show_pillar(minion='*', **kwargs):
'''
Returns the compiled pillar either of a specific minion
or just the global available pillars. This function assumes
that no minion has the id ``*``.
Function also accepts pillarenv as attribute in order to limit to a specific pillar branch of git
CLI Example:
shows minion specific pillar:
.. code-block:: bash
salt-run pillar.show_pillar 'www.example.com'
shows global pillar:
.. code-block:: bash
salt-run pillar.show_pillar
shows global pillar for 'dev' pillar environment:
(note that not specifying pillarenv will merge all pillar environments
using the master config option pillar_source_merging_strategy.)
.. code-block:: bash
salt-run pillar.show_pillar 'pillarenv=dev'
shows global pillar for 'dev' pillar environment and specific pillarenv = dev:
.. code-block:: bash
salt-run pillar.show_pillar 'saltenv=dev' 'pillarenv=dev'
API Example:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
runner = salt.runner.RunnerClient(opts)
pillar = runner.cmd('pillar.show_pillar', [])
print(pillar)
'''
pillarenv = None
saltenv = 'base'
id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__)
if not grains and minion == __opts__['id']:
grains = salt.loader.grains(__opts__)
if grains is None:
grains = {'fqdn': minion}
for key in kwargs:
if key == 'saltenv':
saltenv = kwargs[key]
elif key == 'pillarenv':
# pillarenv overridden on CLI
pillarenv = kwargs[key]
else:
grains[key] = kwargs[key]
pillar = salt.pillar.Pillar(
__opts__,
grains,
id_,
saltenv,
pillarenv=pillarenv)
compiled_pillar = pillar.compile_pillar()
# needed because pillar compilation clobbers grains etc via lazyLoader
# this resets the masterminion back to known state
__salt__['salt.cmd']('sys.reload_modules')
return compiled_pillar
|
Returns the compiled pillar either of a specific minion
or just the global available pillars. This function assumes
that no minion has the id ``*``.
Function also accepts pillarenv as attribute in order to limit to a specific pillar branch of git
CLI Example:
shows minion specific pillar:
.. code-block:: bash
salt-run pillar.show_pillar 'www.example.com'
shows global pillar:
.. code-block:: bash
salt-run pillar.show_pillar
shows global pillar for 'dev' pillar environment:
(note that not specifying pillarenv will merge all pillar environments
using the master config option pillar_source_merging_strategy.)
.. code-block:: bash
salt-run pillar.show_pillar 'pillarenv=dev'
shows global pillar for 'dev' pillar environment and specific pillarenv = dev:
.. code-block:: bash
salt-run pillar.show_pillar 'saltenv=dev' 'pillarenv=dev'
API Example:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
runner = salt.runner.RunnerClient(opts)
pillar = runner.cmd('pillar.show_pillar', [])
print(pillar)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/pillar.py#L46-L122
|
[
"def get_minion_data(minion, opts):\n '''\n Get the grains/pillar for a specific minion. If minion is None, it\n will return the grains/pillar for the first minion it finds.\n\n Return value is a tuple of the minion ID, grains, and pillar\n '''\n grains = None\n pillar = None\n if opts.get('minion_data_cache', False):\n cache = salt.cache.factory(opts)\n if minion is None:\n for id_ in cache.list('minions'):\n data = cache.fetch('minions/{0}'.format(id_), 'data')\n if data is None:\n continue\n else:\n data = cache.fetch('minions/{0}'.format(minion), 'data')\n if data is not None:\n grains = data.get('grains', None)\n pillar = data.get('pillar', None)\n return minion if minion else None, grains, pillar\n",
"def compile_pillar(self, ext=True):\n '''\n Render the pillar data and return\n '''\n top, top_errors = self.get_top()\n if ext:\n if self.opts.get('ext_pillar_first', False):\n self.opts['pillar'], errors = self.ext_pillar(self.pillar_override)\n self.rend = salt.loader.render(self.opts, self.functions)\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches, errors=errors)\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n pillar, errors = self.ext_pillar(pillar, errors=errors)\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n errors.extend(top_errors)\n if self.opts.get('pillar_opts', False):\n mopts = dict(self.opts)\n if 'grains' in mopts:\n mopts.pop('grains')\n mopts['saltversion'] = __version__\n pillar['master'] = mopts\n if 'pillar' in self.opts and self.opts.get('ssh_merge_pillar', False):\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n if errors:\n for error in errors:\n log.critical('Pillar render error: %s', error)\n pillar['_errors'] = errors\n\n if self.pillar_override:\n pillar = merge(\n pillar,\n self.pillar_override,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n\n decrypt_errors = self.decrypt_pillar(pillar)\n if decrypt_errors:\n pillar.setdefault('_errors', []).extend(decrypt_errors)\n\n return pillar\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to interact with the pillar compiler on the master
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.pillar
import salt.loader
import salt.utils.minions
def show_top(minion=None, saltenv='base'):
'''
Returns the compiled top data for pillar for a specific minion. If no
minion is specified, we use the first minion we find.
CLI Example:
.. code-block:: bash
salt-run pillar.show_top
'''
id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__)
if not grains and minion == __opts__['id']:
grains = salt.loader.grains(__opts__)
pillar = salt.pillar.Pillar(
__opts__,
grains,
id_,
saltenv)
top, errors = pillar.get_top()
if errors:
__jid_event__.fire_event({'data': errors, 'outputter': 'nested'}, 'progress')
return errors
# needed because pillar compilation clobbers grains etc via lazyLoader
# this resets the masterminion back to known state
__salt__['salt.cmd']('sys.reload_modules')
return top
|
saltstack/salt
|
salt/modules/rvm.py
|
install
|
python
|
def install(runas=None):
'''
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
'''
# RVM dependencies on Ubuntu 10.04:
# bash coreutils gzip bzip2 gawk sed curl git-core subversion
installer = 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer'
ret = __salt__['cmd.run_all'](
# the RVM installer automatically does a multi-user install when it is
# invoked with root privileges
'curl -Ls {installer} | bash -s stable'.format(installer=installer),
runas=runas,
python_shell=True
)
if ret['retcode'] > 0:
msg = 'Error encountered while downloading the RVM installer'
if ret['stderr']:
msg += '. stderr follows:\n\n' + ret['stderr']
raise CommandExecutionError(msg)
return True
|
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rvm.py#L79-L108
| null |
# -*- coding: utf-8 -*-
'''
Manage ruby installations and gemsets with RVM, the Ruby Version Manager.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import os
import logging
# Import salt libs
import salt.utils.args
from salt.exceptions import CommandExecutionError
# Import 3rd party libs
from salt.ext import six
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rvm.runas': None,
}
def _get_rvm_location(runas=None):
if runas:
runas_home = os.path.expanduser('~{0}'.format(runas))
rvmpath = '{0}/.rvm/bin/rvm'.format(runas_home)
if os.path.exists(rvmpath):
return [rvmpath]
return ['/usr/local/rvm/bin/rvm']
def _rvm(command, runas=None, cwd=None, env=None):
if runas is None:
runas = __salt__['config.option']('rvm.runas')
if not is_installed(runas):
return False
cmd = _get_rvm_location(runas) + command
ret = __salt__['cmd.run_all'](cmd,
runas=runas,
cwd=cwd,
python_shell=False,
env=env)
if ret['retcode'] == 0:
return ret['stdout']
return False
def _rvm_do(ruby, command, runas=None, cwd=None, env=None):
return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)
def is_installed(runas=None):
'''
Check if RVM is installed.
CLI Example:
.. code-block:: bash
salt '*' rvm.is_installed
'''
try:
return __salt__['cmd.has_exec'](_get_rvm_location(runas)[0])
except IndexError:
return False
def install_ruby(ruby, runas=None, opts=None, env=None):
'''
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to set for the install command. Useful for exporting compilation
flags such as RUBY_CONFIGURE_OPTS
opts
List of options to pass to the RVM installer (ie -C, --patch, etc)
CLI Example:
.. code-block:: bash
salt '*' rvm.install_ruby 1.9.3-p385
'''
# MRI/RBX/REE dependencies for Ubuntu 10.04:
# build-essential openssl libreadline6 libreadline6-dev curl
# git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0
# libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev autoconf libc6-dev
# libncurses5-dev automake libtool bison subversion ruby
if opts is None:
opts = []
if runas and runas != 'root':
_rvm(['autolibs', 'disable', ruby] + opts, runas=runas)
opts.append('--disable-binary')
return _rvm(['install', ruby] + opts, runas=runas, env=env)
def reinstall_ruby(ruby, runas=None, env=None):
'''
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.reinstall_ruby 1.9.3-p385
'''
return _rvm(['reinstall', ruby], runas=runas, env=env)
def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile(r'^[= ]([*> ]) ([^- ]+)-([^ ]+) \[ (.*) \]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([
match.group(2), match.group(3), match.group(1) == '*'
])
return rubies
def set_default(ruby, runas=None):
'''
Set the default ruby
ruby
The version of ruby to make the default
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.set_default 2.0.0
'''
return _rvm(['alias', 'create', 'default', ruby], runas=runas)
def get(version='stable', runas=None):
'''
Update RVM
version : stable
Which version of RVM to install, (e.g. stable or head)
CLI Example:
.. code-block:: bash
salt '*' rvm.get
'''
return _rvm(['get', version], runas=runas)
def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
binaries : None
The names of the binaries to create wrappers for. When nothing is
given, wrappers for ruby, gem, rake, irb, rdoc, ri and testrb are
generated.
CLI Example:
.. code-block:: bash
salt '*' rvm.wrapper <ruby_string> <wrapper_prefix>
'''
cmd = ['wrapper', ruby_string, wrapper_prefix]
cmd.extend(binaries)
return _rvm(cmd, runas=runas)
def rubygems(ruby, version, runas=None):
'''
Installs a specific rubygems version in the given ruby
ruby
The ruby for which to install rubygems
version
The version of rubygems to install, or 'remove' to use the version that
ships with 1.9
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.rubygems 2.0.0 1.8.24
'''
return _rvm_do(ruby, ['rubygems', version], runas=runas)
def gemset_create(ruby, gemset, runas=None):
'''
Creates a gemset.
ruby
The ruby version for which to create the gemset
gemset
The name of the gemset to create
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_create 2.0.0 foobar
'''
return _rvm_do(ruby, ['rvm', 'gemset', 'create', gemset], runas=runas)
def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list
'''
gemsets = []
output = _rvm_do(ruby, ['rvm', 'gemset', 'list'], runas=runas)
if output:
regex = re.compile('^ ([^ ]+)')
for line in output.splitlines():
match = regex.match(line)
if match:
gemsets.append(match.group(1))
return gemsets
def gemset_delete(ruby, gemset, runas=None):
'''
Delete a gemset
ruby
The ruby version to which the gemset belongs
gemset
The gemset to delete
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_delete 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'delete', gemset],
runas=runas)
def gemset_empty(ruby, gemset, runas=None):
'''
Remove all gems from a gemset.
ruby
The ruby version to which the gemset belongs
gemset
The gemset to empty
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_empty 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'empty', gemset],
runas=runas)
def gemset_copy(source, destination, runas=None):
'''
Copy all gems from one gemset to another.
source
The name of the gemset to copy, complete with ruby version
destination
The destination gemset
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_copy foobar bazquo
'''
return _rvm(['gemset', 'copy', source, destination], runas=runas)
def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list_all
'''
gemsets = {}
current_ruby = None
output = _rvm_do('default', ['rvm', 'gemset', 'list_all'], runas=runas)
if output:
gems_regex = re.compile('^ ([^ ]+)')
gemset_regex = re.compile('^gemsets for ([^ ]+)')
for line in output.splitlines():
match = gemset_regex.match(line)
if match:
current_ruby = match.group(1)
gemsets[current_ruby] = []
match = gems_regex.match(line)
if match:
gemsets[current_ruby].append(match.group(1))
return gemsets
def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to run the rvm command. Defaults to the user's
home directory.
CLI Example:
.. code-block:: bash
salt '*' rvm.do 2.0.0 <command>
'''
try:
command = salt.utils.args.shlex_split(command)
except AttributeError:
command = salt.utils.args.shlex_split(six.text_type(command))
return _rvm_do(ruby, command, runas=runas, cwd=cwd, env=env)
|
saltstack/salt
|
salt/modules/rvm.py
|
install_ruby
|
python
|
def install_ruby(ruby, runas=None, opts=None, env=None):
'''
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to set for the install command. Useful for exporting compilation
flags such as RUBY_CONFIGURE_OPTS
opts
List of options to pass to the RVM installer (ie -C, --patch, etc)
CLI Example:
.. code-block:: bash
salt '*' rvm.install_ruby 1.9.3-p385
'''
# MRI/RBX/REE dependencies for Ubuntu 10.04:
# build-essential openssl libreadline6 libreadline6-dev curl
# git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0
# libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev autoconf libc6-dev
# libncurses5-dev automake libtool bison subversion ruby
if opts is None:
opts = []
if runas and runas != 'root':
_rvm(['autolibs', 'disable', ruby] + opts, runas=runas)
opts.append('--disable-binary')
return _rvm(['install', ruby] + opts, runas=runas, env=env)
|
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to set for the install command. Useful for exporting compilation
flags such as RUBY_CONFIGURE_OPTS
opts
List of options to pass to the RVM installer (ie -C, --patch, etc)
CLI Example:
.. code-block:: bash
salt '*' rvm.install_ruby 1.9.3-p385
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rvm.py#L111-L146
|
[
"def _rvm(command, runas=None, cwd=None, env=None):\n if runas is None:\n runas = __salt__['config.option']('rvm.runas')\n if not is_installed(runas):\n return False\n\n cmd = _get_rvm_location(runas) + command\n\n ret = __salt__['cmd.run_all'](cmd,\n runas=runas,\n cwd=cwd,\n python_shell=False,\n env=env)\n\n if ret['retcode'] == 0:\n return ret['stdout']\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations and gemsets with RVM, the Ruby Version Manager.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import os
import logging
# Import salt libs
import salt.utils.args
from salt.exceptions import CommandExecutionError
# Import 3rd party libs
from salt.ext import six
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rvm.runas': None,
}
def _get_rvm_location(runas=None):
if runas:
runas_home = os.path.expanduser('~{0}'.format(runas))
rvmpath = '{0}/.rvm/bin/rvm'.format(runas_home)
if os.path.exists(rvmpath):
return [rvmpath]
return ['/usr/local/rvm/bin/rvm']
def _rvm(command, runas=None, cwd=None, env=None):
if runas is None:
runas = __salt__['config.option']('rvm.runas')
if not is_installed(runas):
return False
cmd = _get_rvm_location(runas) + command
ret = __salt__['cmd.run_all'](cmd,
runas=runas,
cwd=cwd,
python_shell=False,
env=env)
if ret['retcode'] == 0:
return ret['stdout']
return False
def _rvm_do(ruby, command, runas=None, cwd=None, env=None):
return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)
def is_installed(runas=None):
'''
Check if RVM is installed.
CLI Example:
.. code-block:: bash
salt '*' rvm.is_installed
'''
try:
return __salt__['cmd.has_exec'](_get_rvm_location(runas)[0])
except IndexError:
return False
def install(runas=None):
'''
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
'''
# RVM dependencies on Ubuntu 10.04:
# bash coreutils gzip bzip2 gawk sed curl git-core subversion
installer = 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer'
ret = __salt__['cmd.run_all'](
# the RVM installer automatically does a multi-user install when it is
# invoked with root privileges
'curl -Ls {installer} | bash -s stable'.format(installer=installer),
runas=runas,
python_shell=True
)
if ret['retcode'] > 0:
msg = 'Error encountered while downloading the RVM installer'
if ret['stderr']:
msg += '. stderr follows:\n\n' + ret['stderr']
raise CommandExecutionError(msg)
return True
def reinstall_ruby(ruby, runas=None, env=None):
'''
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.reinstall_ruby 1.9.3-p385
'''
return _rvm(['reinstall', ruby], runas=runas, env=env)
def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile(r'^[= ]([*> ]) ([^- ]+)-([^ ]+) \[ (.*) \]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([
match.group(2), match.group(3), match.group(1) == '*'
])
return rubies
def set_default(ruby, runas=None):
'''
Set the default ruby
ruby
The version of ruby to make the default
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.set_default 2.0.0
'''
return _rvm(['alias', 'create', 'default', ruby], runas=runas)
def get(version='stable', runas=None):
'''
Update RVM
version : stable
Which version of RVM to install, (e.g. stable or head)
CLI Example:
.. code-block:: bash
salt '*' rvm.get
'''
return _rvm(['get', version], runas=runas)
def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
binaries : None
The names of the binaries to create wrappers for. When nothing is
given, wrappers for ruby, gem, rake, irb, rdoc, ri and testrb are
generated.
CLI Example:
.. code-block:: bash
salt '*' rvm.wrapper <ruby_string> <wrapper_prefix>
'''
cmd = ['wrapper', ruby_string, wrapper_prefix]
cmd.extend(binaries)
return _rvm(cmd, runas=runas)
def rubygems(ruby, version, runas=None):
'''
Installs a specific rubygems version in the given ruby
ruby
The ruby for which to install rubygems
version
The version of rubygems to install, or 'remove' to use the version that
ships with 1.9
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.rubygems 2.0.0 1.8.24
'''
return _rvm_do(ruby, ['rubygems', version], runas=runas)
def gemset_create(ruby, gemset, runas=None):
'''
Creates a gemset.
ruby
The ruby version for which to create the gemset
gemset
The name of the gemset to create
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_create 2.0.0 foobar
'''
return _rvm_do(ruby, ['rvm', 'gemset', 'create', gemset], runas=runas)
def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list
'''
gemsets = []
output = _rvm_do(ruby, ['rvm', 'gemset', 'list'], runas=runas)
if output:
regex = re.compile('^ ([^ ]+)')
for line in output.splitlines():
match = regex.match(line)
if match:
gemsets.append(match.group(1))
return gemsets
def gemset_delete(ruby, gemset, runas=None):
'''
Delete a gemset
ruby
The ruby version to which the gemset belongs
gemset
The gemset to delete
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_delete 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'delete', gemset],
runas=runas)
def gemset_empty(ruby, gemset, runas=None):
'''
Remove all gems from a gemset.
ruby
The ruby version to which the gemset belongs
gemset
The gemset to empty
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_empty 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'empty', gemset],
runas=runas)
def gemset_copy(source, destination, runas=None):
'''
Copy all gems from one gemset to another.
source
The name of the gemset to copy, complete with ruby version
destination
The destination gemset
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_copy foobar bazquo
'''
return _rvm(['gemset', 'copy', source, destination], runas=runas)
def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list_all
'''
gemsets = {}
current_ruby = None
output = _rvm_do('default', ['rvm', 'gemset', 'list_all'], runas=runas)
if output:
gems_regex = re.compile('^ ([^ ]+)')
gemset_regex = re.compile('^gemsets for ([^ ]+)')
for line in output.splitlines():
match = gemset_regex.match(line)
if match:
current_ruby = match.group(1)
gemsets[current_ruby] = []
match = gems_regex.match(line)
if match:
gemsets[current_ruby].append(match.group(1))
return gemsets
def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to run the rvm command. Defaults to the user's
home directory.
CLI Example:
.. code-block:: bash
salt '*' rvm.do 2.0.0 <command>
'''
try:
command = salt.utils.args.shlex_split(command)
except AttributeError:
command = salt.utils.args.shlex_split(six.text_type(command))
return _rvm_do(ruby, command, runas=runas, cwd=cwd, env=env)
|
saltstack/salt
|
salt/modules/rvm.py
|
reinstall_ruby
|
python
|
def reinstall_ruby(ruby, runas=None, env=None):
'''
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.reinstall_ruby 1.9.3-p385
'''
return _rvm(['reinstall', ruby], runas=runas, env=env)
|
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.reinstall_ruby 1.9.3-p385
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rvm.py#L149-L166
|
[
"def _rvm(command, runas=None, cwd=None, env=None):\n if runas is None:\n runas = __salt__['config.option']('rvm.runas')\n if not is_installed(runas):\n return False\n\n cmd = _get_rvm_location(runas) + command\n\n ret = __salt__['cmd.run_all'](cmd,\n runas=runas,\n cwd=cwd,\n python_shell=False,\n env=env)\n\n if ret['retcode'] == 0:\n return ret['stdout']\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations and gemsets with RVM, the Ruby Version Manager.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import os
import logging
# Import salt libs
import salt.utils.args
from salt.exceptions import CommandExecutionError
# Import 3rd party libs
from salt.ext import six
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rvm.runas': None,
}
def _get_rvm_location(runas=None):
if runas:
runas_home = os.path.expanduser('~{0}'.format(runas))
rvmpath = '{0}/.rvm/bin/rvm'.format(runas_home)
if os.path.exists(rvmpath):
return [rvmpath]
return ['/usr/local/rvm/bin/rvm']
def _rvm(command, runas=None, cwd=None, env=None):
if runas is None:
runas = __salt__['config.option']('rvm.runas')
if not is_installed(runas):
return False
cmd = _get_rvm_location(runas) + command
ret = __salt__['cmd.run_all'](cmd,
runas=runas,
cwd=cwd,
python_shell=False,
env=env)
if ret['retcode'] == 0:
return ret['stdout']
return False
def _rvm_do(ruby, command, runas=None, cwd=None, env=None):
return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)
def is_installed(runas=None):
'''
Check if RVM is installed.
CLI Example:
.. code-block:: bash
salt '*' rvm.is_installed
'''
try:
return __salt__['cmd.has_exec'](_get_rvm_location(runas)[0])
except IndexError:
return False
def install(runas=None):
'''
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
'''
# RVM dependencies on Ubuntu 10.04:
# bash coreutils gzip bzip2 gawk sed curl git-core subversion
installer = 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer'
ret = __salt__['cmd.run_all'](
# the RVM installer automatically does a multi-user install when it is
# invoked with root privileges
'curl -Ls {installer} | bash -s stable'.format(installer=installer),
runas=runas,
python_shell=True
)
if ret['retcode'] > 0:
msg = 'Error encountered while downloading the RVM installer'
if ret['stderr']:
msg += '. stderr follows:\n\n' + ret['stderr']
raise CommandExecutionError(msg)
return True
def install_ruby(ruby, runas=None, opts=None, env=None):
'''
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to set for the install command. Useful for exporting compilation
flags such as RUBY_CONFIGURE_OPTS
opts
List of options to pass to the RVM installer (ie -C, --patch, etc)
CLI Example:
.. code-block:: bash
salt '*' rvm.install_ruby 1.9.3-p385
'''
# MRI/RBX/REE dependencies for Ubuntu 10.04:
# build-essential openssl libreadline6 libreadline6-dev curl
# git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0
# libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev autoconf libc6-dev
# libncurses5-dev automake libtool bison subversion ruby
if opts is None:
opts = []
if runas and runas != 'root':
_rvm(['autolibs', 'disable', ruby] + opts, runas=runas)
opts.append('--disable-binary')
return _rvm(['install', ruby] + opts, runas=runas, env=env)
def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile(r'^[= ]([*> ]) ([^- ]+)-([^ ]+) \[ (.*) \]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([
match.group(2), match.group(3), match.group(1) == '*'
])
return rubies
def set_default(ruby, runas=None):
'''
Set the default ruby
ruby
The version of ruby to make the default
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.set_default 2.0.0
'''
return _rvm(['alias', 'create', 'default', ruby], runas=runas)
def get(version='stable', runas=None):
'''
Update RVM
version : stable
Which version of RVM to install, (e.g. stable or head)
CLI Example:
.. code-block:: bash
salt '*' rvm.get
'''
return _rvm(['get', version], runas=runas)
def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
binaries : None
The names of the binaries to create wrappers for. When nothing is
given, wrappers for ruby, gem, rake, irb, rdoc, ri and testrb are
generated.
CLI Example:
.. code-block:: bash
salt '*' rvm.wrapper <ruby_string> <wrapper_prefix>
'''
cmd = ['wrapper', ruby_string, wrapper_prefix]
cmd.extend(binaries)
return _rvm(cmd, runas=runas)
def rubygems(ruby, version, runas=None):
'''
Installs a specific rubygems version in the given ruby
ruby
The ruby for which to install rubygems
version
The version of rubygems to install, or 'remove' to use the version that
ships with 1.9
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.rubygems 2.0.0 1.8.24
'''
return _rvm_do(ruby, ['rubygems', version], runas=runas)
def gemset_create(ruby, gemset, runas=None):
'''
Creates a gemset.
ruby
The ruby version for which to create the gemset
gemset
The name of the gemset to create
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_create 2.0.0 foobar
'''
return _rvm_do(ruby, ['rvm', 'gemset', 'create', gemset], runas=runas)
def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list
'''
gemsets = []
output = _rvm_do(ruby, ['rvm', 'gemset', 'list'], runas=runas)
if output:
regex = re.compile('^ ([^ ]+)')
for line in output.splitlines():
match = regex.match(line)
if match:
gemsets.append(match.group(1))
return gemsets
def gemset_delete(ruby, gemset, runas=None):
'''
Delete a gemset
ruby
The ruby version to which the gemset belongs
gemset
The gemset to delete
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_delete 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'delete', gemset],
runas=runas)
def gemset_empty(ruby, gemset, runas=None):
'''
Remove all gems from a gemset.
ruby
The ruby version to which the gemset belongs
gemset
The gemset to empty
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_empty 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'empty', gemset],
runas=runas)
def gemset_copy(source, destination, runas=None):
'''
Copy all gems from one gemset to another.
source
The name of the gemset to copy, complete with ruby version
destination
The destination gemset
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_copy foobar bazquo
'''
return _rvm(['gemset', 'copy', source, destination], runas=runas)
def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list_all
'''
gemsets = {}
current_ruby = None
output = _rvm_do('default', ['rvm', 'gemset', 'list_all'], runas=runas)
if output:
gems_regex = re.compile('^ ([^ ]+)')
gemset_regex = re.compile('^gemsets for ([^ ]+)')
for line in output.splitlines():
match = gemset_regex.match(line)
if match:
current_ruby = match.group(1)
gemsets[current_ruby] = []
match = gems_regex.match(line)
if match:
gemsets[current_ruby].append(match.group(1))
return gemsets
def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to run the rvm command. Defaults to the user's
home directory.
CLI Example:
.. code-block:: bash
salt '*' rvm.do 2.0.0 <command>
'''
try:
command = salt.utils.args.shlex_split(command)
except AttributeError:
command = salt.utils.args.shlex_split(six.text_type(command))
return _rvm_do(ruby, command, runas=runas, cwd=cwd, env=env)
|
saltstack/salt
|
salt/modules/rvm.py
|
list_
|
python
|
def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile(r'^[= ]([*> ]) ([^- ]+)-([^ ]+) \[ (.*) \]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([
match.group(2), match.group(3), match.group(1) == '*'
])
return rubies
|
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rvm.py#L169-L193
|
[
"def _rvm(command, runas=None, cwd=None, env=None):\n if runas is None:\n runas = __salt__['config.option']('rvm.runas')\n if not is_installed(runas):\n return False\n\n cmd = _get_rvm_location(runas) + command\n\n ret = __salt__['cmd.run_all'](cmd,\n runas=runas,\n cwd=cwd,\n python_shell=False,\n env=env)\n\n if ret['retcode'] == 0:\n return ret['stdout']\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations and gemsets with RVM, the Ruby Version Manager.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import os
import logging
# Import salt libs
import salt.utils.args
from salt.exceptions import CommandExecutionError
# Import 3rd party libs
from salt.ext import six
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rvm.runas': None,
}
def _get_rvm_location(runas=None):
if runas:
runas_home = os.path.expanduser('~{0}'.format(runas))
rvmpath = '{0}/.rvm/bin/rvm'.format(runas_home)
if os.path.exists(rvmpath):
return [rvmpath]
return ['/usr/local/rvm/bin/rvm']
def _rvm(command, runas=None, cwd=None, env=None):
if runas is None:
runas = __salt__['config.option']('rvm.runas')
if not is_installed(runas):
return False
cmd = _get_rvm_location(runas) + command
ret = __salt__['cmd.run_all'](cmd,
runas=runas,
cwd=cwd,
python_shell=False,
env=env)
if ret['retcode'] == 0:
return ret['stdout']
return False
def _rvm_do(ruby, command, runas=None, cwd=None, env=None):
return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)
def is_installed(runas=None):
'''
Check if RVM is installed.
CLI Example:
.. code-block:: bash
salt '*' rvm.is_installed
'''
try:
return __salt__['cmd.has_exec'](_get_rvm_location(runas)[0])
except IndexError:
return False
def install(runas=None):
'''
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
'''
# RVM dependencies on Ubuntu 10.04:
# bash coreutils gzip bzip2 gawk sed curl git-core subversion
installer = 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer'
ret = __salt__['cmd.run_all'](
# the RVM installer automatically does a multi-user install when it is
# invoked with root privileges
'curl -Ls {installer} | bash -s stable'.format(installer=installer),
runas=runas,
python_shell=True
)
if ret['retcode'] > 0:
msg = 'Error encountered while downloading the RVM installer'
if ret['stderr']:
msg += '. stderr follows:\n\n' + ret['stderr']
raise CommandExecutionError(msg)
return True
def install_ruby(ruby, runas=None, opts=None, env=None):
'''
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to set for the install command. Useful for exporting compilation
flags such as RUBY_CONFIGURE_OPTS
opts
List of options to pass to the RVM installer (ie -C, --patch, etc)
CLI Example:
.. code-block:: bash
salt '*' rvm.install_ruby 1.9.3-p385
'''
# MRI/RBX/REE dependencies for Ubuntu 10.04:
# build-essential openssl libreadline6 libreadline6-dev curl
# git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0
# libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev autoconf libc6-dev
# libncurses5-dev automake libtool bison subversion ruby
if opts is None:
opts = []
if runas and runas != 'root':
_rvm(['autolibs', 'disable', ruby] + opts, runas=runas)
opts.append('--disable-binary')
return _rvm(['install', ruby] + opts, runas=runas, env=env)
def reinstall_ruby(ruby, runas=None, env=None):
'''
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.reinstall_ruby 1.9.3-p385
'''
return _rvm(['reinstall', ruby], runas=runas, env=env)
def set_default(ruby, runas=None):
'''
Set the default ruby
ruby
The version of ruby to make the default
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.set_default 2.0.0
'''
return _rvm(['alias', 'create', 'default', ruby], runas=runas)
def get(version='stable', runas=None):
'''
Update RVM
version : stable
Which version of RVM to install, (e.g. stable or head)
CLI Example:
.. code-block:: bash
salt '*' rvm.get
'''
return _rvm(['get', version], runas=runas)
def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
binaries : None
The names of the binaries to create wrappers for. When nothing is
given, wrappers for ruby, gem, rake, irb, rdoc, ri and testrb are
generated.
CLI Example:
.. code-block:: bash
salt '*' rvm.wrapper <ruby_string> <wrapper_prefix>
'''
cmd = ['wrapper', ruby_string, wrapper_prefix]
cmd.extend(binaries)
return _rvm(cmd, runas=runas)
def rubygems(ruby, version, runas=None):
'''
Installs a specific rubygems version in the given ruby
ruby
The ruby for which to install rubygems
version
The version of rubygems to install, or 'remove' to use the version that
ships with 1.9
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.rubygems 2.0.0 1.8.24
'''
return _rvm_do(ruby, ['rubygems', version], runas=runas)
def gemset_create(ruby, gemset, runas=None):
'''
Creates a gemset.
ruby
The ruby version for which to create the gemset
gemset
The name of the gemset to create
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_create 2.0.0 foobar
'''
return _rvm_do(ruby, ['rvm', 'gemset', 'create', gemset], runas=runas)
def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list
'''
gemsets = []
output = _rvm_do(ruby, ['rvm', 'gemset', 'list'], runas=runas)
if output:
regex = re.compile('^ ([^ ]+)')
for line in output.splitlines():
match = regex.match(line)
if match:
gemsets.append(match.group(1))
return gemsets
def gemset_delete(ruby, gemset, runas=None):
'''
Delete a gemset
ruby
The ruby version to which the gemset belongs
gemset
The gemset to delete
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_delete 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'delete', gemset],
runas=runas)
def gemset_empty(ruby, gemset, runas=None):
'''
Remove all gems from a gemset.
ruby
The ruby version to which the gemset belongs
gemset
The gemset to empty
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_empty 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'empty', gemset],
runas=runas)
def gemset_copy(source, destination, runas=None):
'''
Copy all gems from one gemset to another.
source
The name of the gemset to copy, complete with ruby version
destination
The destination gemset
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_copy foobar bazquo
'''
return _rvm(['gemset', 'copy', source, destination], runas=runas)
def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list_all
'''
gemsets = {}
current_ruby = None
output = _rvm_do('default', ['rvm', 'gemset', 'list_all'], runas=runas)
if output:
gems_regex = re.compile('^ ([^ ]+)')
gemset_regex = re.compile('^gemsets for ([^ ]+)')
for line in output.splitlines():
match = gemset_regex.match(line)
if match:
current_ruby = match.group(1)
gemsets[current_ruby] = []
match = gems_regex.match(line)
if match:
gemsets[current_ruby].append(match.group(1))
return gemsets
def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to run the rvm command. Defaults to the user's
home directory.
CLI Example:
.. code-block:: bash
salt '*' rvm.do 2.0.0 <command>
'''
try:
command = salt.utils.args.shlex_split(command)
except AttributeError:
command = salt.utils.args.shlex_split(six.text_type(command))
return _rvm_do(ruby, command, runas=runas, cwd=cwd, env=env)
|
saltstack/salt
|
salt/modules/rvm.py
|
wrapper
|
python
|
def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
binaries : None
The names of the binaries to create wrappers for. When nothing is
given, wrappers for ruby, gem, rake, irb, rdoc, ri and testrb are
generated.
CLI Example:
.. code-block:: bash
salt '*' rvm.wrapper <ruby_string> <wrapper_prefix>
'''
cmd = ['wrapper', ruby_string, wrapper_prefix]
cmd.extend(binaries)
return _rvm(cmd, runas=runas)
|
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
binaries : None
The names of the binaries to create wrappers for. When nothing is
given, wrappers for ruby, gem, rake, irb, rdoc, ri and testrb are
generated.
CLI Example:
.. code-block:: bash
salt '*' rvm.wrapper <ruby_string> <wrapper_prefix>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rvm.py#L232-L259
|
[
"def _rvm(command, runas=None, cwd=None, env=None):\n if runas is None:\n runas = __salt__['config.option']('rvm.runas')\n if not is_installed(runas):\n return False\n\n cmd = _get_rvm_location(runas) + command\n\n ret = __salt__['cmd.run_all'](cmd,\n runas=runas,\n cwd=cwd,\n python_shell=False,\n env=env)\n\n if ret['retcode'] == 0:\n return ret['stdout']\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations and gemsets with RVM, the Ruby Version Manager.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import os
import logging
# Import salt libs
import salt.utils.args
from salt.exceptions import CommandExecutionError
# Import 3rd party libs
from salt.ext import six
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rvm.runas': None,
}
def _get_rvm_location(runas=None):
if runas:
runas_home = os.path.expanduser('~{0}'.format(runas))
rvmpath = '{0}/.rvm/bin/rvm'.format(runas_home)
if os.path.exists(rvmpath):
return [rvmpath]
return ['/usr/local/rvm/bin/rvm']
def _rvm(command, runas=None, cwd=None, env=None):
if runas is None:
runas = __salt__['config.option']('rvm.runas')
if not is_installed(runas):
return False
cmd = _get_rvm_location(runas) + command
ret = __salt__['cmd.run_all'](cmd,
runas=runas,
cwd=cwd,
python_shell=False,
env=env)
if ret['retcode'] == 0:
return ret['stdout']
return False
def _rvm_do(ruby, command, runas=None, cwd=None, env=None):
return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)
def is_installed(runas=None):
'''
Check if RVM is installed.
CLI Example:
.. code-block:: bash
salt '*' rvm.is_installed
'''
try:
return __salt__['cmd.has_exec'](_get_rvm_location(runas)[0])
except IndexError:
return False
def install(runas=None):
'''
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
'''
# RVM dependencies on Ubuntu 10.04:
# bash coreutils gzip bzip2 gawk sed curl git-core subversion
installer = 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer'
ret = __salt__['cmd.run_all'](
# the RVM installer automatically does a multi-user install when it is
# invoked with root privileges
'curl -Ls {installer} | bash -s stable'.format(installer=installer),
runas=runas,
python_shell=True
)
if ret['retcode'] > 0:
msg = 'Error encountered while downloading the RVM installer'
if ret['stderr']:
msg += '. stderr follows:\n\n' + ret['stderr']
raise CommandExecutionError(msg)
return True
def install_ruby(ruby, runas=None, opts=None, env=None):
'''
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to set for the install command. Useful for exporting compilation
flags such as RUBY_CONFIGURE_OPTS
opts
List of options to pass to the RVM installer (ie -C, --patch, etc)
CLI Example:
.. code-block:: bash
salt '*' rvm.install_ruby 1.9.3-p385
'''
# MRI/RBX/REE dependencies for Ubuntu 10.04:
# build-essential openssl libreadline6 libreadline6-dev curl
# git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0
# libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev autoconf libc6-dev
# libncurses5-dev automake libtool bison subversion ruby
if opts is None:
opts = []
if runas and runas != 'root':
_rvm(['autolibs', 'disable', ruby] + opts, runas=runas)
opts.append('--disable-binary')
return _rvm(['install', ruby] + opts, runas=runas, env=env)
def reinstall_ruby(ruby, runas=None, env=None):
'''
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.reinstall_ruby 1.9.3-p385
'''
return _rvm(['reinstall', ruby], runas=runas, env=env)
def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile(r'^[= ]([*> ]) ([^- ]+)-([^ ]+) \[ (.*) \]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([
match.group(2), match.group(3), match.group(1) == '*'
])
return rubies
def set_default(ruby, runas=None):
'''
Set the default ruby
ruby
The version of ruby to make the default
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.set_default 2.0.0
'''
return _rvm(['alias', 'create', 'default', ruby], runas=runas)
def get(version='stable', runas=None):
'''
Update RVM
version : stable
Which version of RVM to install, (e.g. stable or head)
CLI Example:
.. code-block:: bash
salt '*' rvm.get
'''
return _rvm(['get', version], runas=runas)
def rubygems(ruby, version, runas=None):
'''
Installs a specific rubygems version in the given ruby
ruby
The ruby for which to install rubygems
version
The version of rubygems to install, or 'remove' to use the version that
ships with 1.9
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.rubygems 2.0.0 1.8.24
'''
return _rvm_do(ruby, ['rubygems', version], runas=runas)
def gemset_create(ruby, gemset, runas=None):
'''
Creates a gemset.
ruby
The ruby version for which to create the gemset
gemset
The name of the gemset to create
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_create 2.0.0 foobar
'''
return _rvm_do(ruby, ['rvm', 'gemset', 'create', gemset], runas=runas)
def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list
'''
gemsets = []
output = _rvm_do(ruby, ['rvm', 'gemset', 'list'], runas=runas)
if output:
regex = re.compile('^ ([^ ]+)')
for line in output.splitlines():
match = regex.match(line)
if match:
gemsets.append(match.group(1))
return gemsets
def gemset_delete(ruby, gemset, runas=None):
'''
Delete a gemset
ruby
The ruby version to which the gemset belongs
gemset
The gemset to delete
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_delete 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'delete', gemset],
runas=runas)
def gemset_empty(ruby, gemset, runas=None):
'''
Remove all gems from a gemset.
ruby
The ruby version to which the gemset belongs
gemset
The gemset to empty
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_empty 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'empty', gemset],
runas=runas)
def gemset_copy(source, destination, runas=None):
'''
Copy all gems from one gemset to another.
source
The name of the gemset to copy, complete with ruby version
destination
The destination gemset
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_copy foobar bazquo
'''
return _rvm(['gemset', 'copy', source, destination], runas=runas)
def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list_all
'''
gemsets = {}
current_ruby = None
output = _rvm_do('default', ['rvm', 'gemset', 'list_all'], runas=runas)
if output:
gems_regex = re.compile('^ ([^ ]+)')
gemset_regex = re.compile('^gemsets for ([^ ]+)')
for line in output.splitlines():
match = gemset_regex.match(line)
if match:
current_ruby = match.group(1)
gemsets[current_ruby] = []
match = gems_regex.match(line)
if match:
gemsets[current_ruby].append(match.group(1))
return gemsets
def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to run the rvm command. Defaults to the user's
home directory.
CLI Example:
.. code-block:: bash
salt '*' rvm.do 2.0.0 <command>
'''
try:
command = salt.utils.args.shlex_split(command)
except AttributeError:
command = salt.utils.args.shlex_split(six.text_type(command))
return _rvm_do(ruby, command, runas=runas, cwd=cwd, env=env)
|
saltstack/salt
|
salt/modules/rvm.py
|
gemset_list
|
python
|
def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list
'''
gemsets = []
output = _rvm_do(ruby, ['rvm', 'gemset', 'list'], runas=runas)
if output:
regex = re.compile('^ ([^ ]+)')
for line in output.splitlines():
match = regex.match(line)
if match:
gemsets.append(match.group(1))
return gemsets
|
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rvm.py#L309-L334
|
[
"def _rvm_do(ruby, command, runas=None, cwd=None, env=None):\n return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations and gemsets with RVM, the Ruby Version Manager.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import os
import logging
# Import salt libs
import salt.utils.args
from salt.exceptions import CommandExecutionError
# Import 3rd party libs
from salt.ext import six
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rvm.runas': None,
}
def _get_rvm_location(runas=None):
if runas:
runas_home = os.path.expanduser('~{0}'.format(runas))
rvmpath = '{0}/.rvm/bin/rvm'.format(runas_home)
if os.path.exists(rvmpath):
return [rvmpath]
return ['/usr/local/rvm/bin/rvm']
def _rvm(command, runas=None, cwd=None, env=None):
if runas is None:
runas = __salt__['config.option']('rvm.runas')
if not is_installed(runas):
return False
cmd = _get_rvm_location(runas) + command
ret = __salt__['cmd.run_all'](cmd,
runas=runas,
cwd=cwd,
python_shell=False,
env=env)
if ret['retcode'] == 0:
return ret['stdout']
return False
def _rvm_do(ruby, command, runas=None, cwd=None, env=None):
return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)
def is_installed(runas=None):
'''
Check if RVM is installed.
CLI Example:
.. code-block:: bash
salt '*' rvm.is_installed
'''
try:
return __salt__['cmd.has_exec'](_get_rvm_location(runas)[0])
except IndexError:
return False
def install(runas=None):
'''
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
'''
# RVM dependencies on Ubuntu 10.04:
# bash coreutils gzip bzip2 gawk sed curl git-core subversion
installer = 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer'
ret = __salt__['cmd.run_all'](
# the RVM installer automatically does a multi-user install when it is
# invoked with root privileges
'curl -Ls {installer} | bash -s stable'.format(installer=installer),
runas=runas,
python_shell=True
)
if ret['retcode'] > 0:
msg = 'Error encountered while downloading the RVM installer'
if ret['stderr']:
msg += '. stderr follows:\n\n' + ret['stderr']
raise CommandExecutionError(msg)
return True
def install_ruby(ruby, runas=None, opts=None, env=None):
'''
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to set for the install command. Useful for exporting compilation
flags such as RUBY_CONFIGURE_OPTS
opts
List of options to pass to the RVM installer (ie -C, --patch, etc)
CLI Example:
.. code-block:: bash
salt '*' rvm.install_ruby 1.9.3-p385
'''
# MRI/RBX/REE dependencies for Ubuntu 10.04:
# build-essential openssl libreadline6 libreadline6-dev curl
# git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0
# libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev autoconf libc6-dev
# libncurses5-dev automake libtool bison subversion ruby
if opts is None:
opts = []
if runas and runas != 'root':
_rvm(['autolibs', 'disable', ruby] + opts, runas=runas)
opts.append('--disable-binary')
return _rvm(['install', ruby] + opts, runas=runas, env=env)
def reinstall_ruby(ruby, runas=None, env=None):
'''
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.reinstall_ruby 1.9.3-p385
'''
return _rvm(['reinstall', ruby], runas=runas, env=env)
def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile(r'^[= ]([*> ]) ([^- ]+)-([^ ]+) \[ (.*) \]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([
match.group(2), match.group(3), match.group(1) == '*'
])
return rubies
def set_default(ruby, runas=None):
'''
Set the default ruby
ruby
The version of ruby to make the default
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.set_default 2.0.0
'''
return _rvm(['alias', 'create', 'default', ruby], runas=runas)
def get(version='stable', runas=None):
'''
Update RVM
version : stable
Which version of RVM to install, (e.g. stable or head)
CLI Example:
.. code-block:: bash
salt '*' rvm.get
'''
return _rvm(['get', version], runas=runas)
def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
binaries : None
The names of the binaries to create wrappers for. When nothing is
given, wrappers for ruby, gem, rake, irb, rdoc, ri and testrb are
generated.
CLI Example:
.. code-block:: bash
salt '*' rvm.wrapper <ruby_string> <wrapper_prefix>
'''
cmd = ['wrapper', ruby_string, wrapper_prefix]
cmd.extend(binaries)
return _rvm(cmd, runas=runas)
def rubygems(ruby, version, runas=None):
'''
Installs a specific rubygems version in the given ruby
ruby
The ruby for which to install rubygems
version
The version of rubygems to install, or 'remove' to use the version that
ships with 1.9
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.rubygems 2.0.0 1.8.24
'''
return _rvm_do(ruby, ['rubygems', version], runas=runas)
def gemset_create(ruby, gemset, runas=None):
'''
Creates a gemset.
ruby
The ruby version for which to create the gemset
gemset
The name of the gemset to create
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_create 2.0.0 foobar
'''
return _rvm_do(ruby, ['rvm', 'gemset', 'create', gemset], runas=runas)
def gemset_delete(ruby, gemset, runas=None):
'''
Delete a gemset
ruby
The ruby version to which the gemset belongs
gemset
The gemset to delete
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_delete 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'delete', gemset],
runas=runas)
def gemset_empty(ruby, gemset, runas=None):
'''
Remove all gems from a gemset.
ruby
The ruby version to which the gemset belongs
gemset
The gemset to empty
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_empty 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'empty', gemset],
runas=runas)
def gemset_copy(source, destination, runas=None):
'''
Copy all gems from one gemset to another.
source
The name of the gemset to copy, complete with ruby version
destination
The destination gemset
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_copy foobar bazquo
'''
return _rvm(['gemset', 'copy', source, destination], runas=runas)
def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list_all
'''
gemsets = {}
current_ruby = None
output = _rvm_do('default', ['rvm', 'gemset', 'list_all'], runas=runas)
if output:
gems_regex = re.compile('^ ([^ ]+)')
gemset_regex = re.compile('^gemsets for ([^ ]+)')
for line in output.splitlines():
match = gemset_regex.match(line)
if match:
current_ruby = match.group(1)
gemsets[current_ruby] = []
match = gems_regex.match(line)
if match:
gemsets[current_ruby].append(match.group(1))
return gemsets
def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to run the rvm command. Defaults to the user's
home directory.
CLI Example:
.. code-block:: bash
salt '*' rvm.do 2.0.0 <command>
'''
try:
command = salt.utils.args.shlex_split(command)
except AttributeError:
command = salt.utils.args.shlex_split(six.text_type(command))
return _rvm_do(ruby, command, runas=runas, cwd=cwd, env=env)
|
saltstack/salt
|
salt/modules/rvm.py
|
gemset_list_all
|
python
|
def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list_all
'''
gemsets = {}
current_ruby = None
output = _rvm_do('default', ['rvm', 'gemset', 'list_all'], runas=runas)
if output:
gems_regex = re.compile('^ ([^ ]+)')
gemset_regex = re.compile('^gemsets for ([^ ]+)')
for line in output.splitlines():
match = gemset_regex.match(line)
if match:
current_ruby = match.group(1)
gemsets[current_ruby] = []
match = gems_regex.match(line)
if match:
gemsets[current_ruby].append(match.group(1))
return gemsets
|
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list_all
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rvm.py#L410-L440
|
[
"def _rvm_do(ruby, command, runas=None, cwd=None, env=None):\n return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations and gemsets with RVM, the Ruby Version Manager.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import os
import logging
# Import salt libs
import salt.utils.args
from salt.exceptions import CommandExecutionError
# Import 3rd party libs
from salt.ext import six
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rvm.runas': None,
}
def _get_rvm_location(runas=None):
if runas:
runas_home = os.path.expanduser('~{0}'.format(runas))
rvmpath = '{0}/.rvm/bin/rvm'.format(runas_home)
if os.path.exists(rvmpath):
return [rvmpath]
return ['/usr/local/rvm/bin/rvm']
def _rvm(command, runas=None, cwd=None, env=None):
if runas is None:
runas = __salt__['config.option']('rvm.runas')
if not is_installed(runas):
return False
cmd = _get_rvm_location(runas) + command
ret = __salt__['cmd.run_all'](cmd,
runas=runas,
cwd=cwd,
python_shell=False,
env=env)
if ret['retcode'] == 0:
return ret['stdout']
return False
def _rvm_do(ruby, command, runas=None, cwd=None, env=None):
return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)
def is_installed(runas=None):
'''
Check if RVM is installed.
CLI Example:
.. code-block:: bash
salt '*' rvm.is_installed
'''
try:
return __salt__['cmd.has_exec'](_get_rvm_location(runas)[0])
except IndexError:
return False
def install(runas=None):
'''
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
'''
# RVM dependencies on Ubuntu 10.04:
# bash coreutils gzip bzip2 gawk sed curl git-core subversion
installer = 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer'
ret = __salt__['cmd.run_all'](
# the RVM installer automatically does a multi-user install when it is
# invoked with root privileges
'curl -Ls {installer} | bash -s stable'.format(installer=installer),
runas=runas,
python_shell=True
)
if ret['retcode'] > 0:
msg = 'Error encountered while downloading the RVM installer'
if ret['stderr']:
msg += '. stderr follows:\n\n' + ret['stderr']
raise CommandExecutionError(msg)
return True
def install_ruby(ruby, runas=None, opts=None, env=None):
'''
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to set for the install command. Useful for exporting compilation
flags such as RUBY_CONFIGURE_OPTS
opts
List of options to pass to the RVM installer (ie -C, --patch, etc)
CLI Example:
.. code-block:: bash
salt '*' rvm.install_ruby 1.9.3-p385
'''
# MRI/RBX/REE dependencies for Ubuntu 10.04:
# build-essential openssl libreadline6 libreadline6-dev curl
# git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0
# libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev autoconf libc6-dev
# libncurses5-dev automake libtool bison subversion ruby
if opts is None:
opts = []
if runas and runas != 'root':
_rvm(['autolibs', 'disable', ruby] + opts, runas=runas)
opts.append('--disable-binary')
return _rvm(['install', ruby] + opts, runas=runas, env=env)
def reinstall_ruby(ruby, runas=None, env=None):
'''
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.reinstall_ruby 1.9.3-p385
'''
return _rvm(['reinstall', ruby], runas=runas, env=env)
def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile(r'^[= ]([*> ]) ([^- ]+)-([^ ]+) \[ (.*) \]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([
match.group(2), match.group(3), match.group(1) == '*'
])
return rubies
def set_default(ruby, runas=None):
'''
Set the default ruby
ruby
The version of ruby to make the default
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.set_default 2.0.0
'''
return _rvm(['alias', 'create', 'default', ruby], runas=runas)
def get(version='stable', runas=None):
'''
Update RVM
version : stable
Which version of RVM to install, (e.g. stable or head)
CLI Example:
.. code-block:: bash
salt '*' rvm.get
'''
return _rvm(['get', version], runas=runas)
def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
binaries : None
The names of the binaries to create wrappers for. When nothing is
given, wrappers for ruby, gem, rake, irb, rdoc, ri and testrb are
generated.
CLI Example:
.. code-block:: bash
salt '*' rvm.wrapper <ruby_string> <wrapper_prefix>
'''
cmd = ['wrapper', ruby_string, wrapper_prefix]
cmd.extend(binaries)
return _rvm(cmd, runas=runas)
def rubygems(ruby, version, runas=None):
'''
Installs a specific rubygems version in the given ruby
ruby
The ruby for which to install rubygems
version
The version of rubygems to install, or 'remove' to use the version that
ships with 1.9
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.rubygems 2.0.0 1.8.24
'''
return _rvm_do(ruby, ['rubygems', version], runas=runas)
def gemset_create(ruby, gemset, runas=None):
'''
Creates a gemset.
ruby
The ruby version for which to create the gemset
gemset
The name of the gemset to create
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_create 2.0.0 foobar
'''
return _rvm_do(ruby, ['rvm', 'gemset', 'create', gemset], runas=runas)
def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list
'''
gemsets = []
output = _rvm_do(ruby, ['rvm', 'gemset', 'list'], runas=runas)
if output:
regex = re.compile('^ ([^ ]+)')
for line in output.splitlines():
match = regex.match(line)
if match:
gemsets.append(match.group(1))
return gemsets
def gemset_delete(ruby, gemset, runas=None):
'''
Delete a gemset
ruby
The ruby version to which the gemset belongs
gemset
The gemset to delete
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_delete 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'delete', gemset],
runas=runas)
def gemset_empty(ruby, gemset, runas=None):
'''
Remove all gems from a gemset.
ruby
The ruby version to which the gemset belongs
gemset
The gemset to empty
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_empty 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'empty', gemset],
runas=runas)
def gemset_copy(source, destination, runas=None):
'''
Copy all gems from one gemset to another.
source
The name of the gemset to copy, complete with ruby version
destination
The destination gemset
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_copy foobar bazquo
'''
return _rvm(['gemset', 'copy', source, destination], runas=runas)
def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to run the rvm command. Defaults to the user's
home directory.
CLI Example:
.. code-block:: bash
salt '*' rvm.do 2.0.0 <command>
'''
try:
command = salt.utils.args.shlex_split(command)
except AttributeError:
command = salt.utils.args.shlex_split(six.text_type(command))
return _rvm_do(ruby, command, runas=runas, cwd=cwd, env=env)
|
saltstack/salt
|
salt/modules/rvm.py
|
do
|
python
|
def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to run the rvm command. Defaults to the user's
home directory.
CLI Example:
.. code-block:: bash
salt '*' rvm.do 2.0.0 <command>
'''
try:
command = salt.utils.args.shlex_split(command)
except AttributeError:
command = salt.utils.args.shlex_split(six.text_type(command))
return _rvm_do(ruby, command, runas=runas, cwd=cwd, env=env)
|
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to run the rvm command. Defaults to the user's
home directory.
CLI Example:
.. code-block:: bash
salt '*' rvm.do 2.0.0 <command>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rvm.py#L443-L471
|
[
"def shlex_split(s, **kwargs):\n '''\n Only split if variable is a string\n '''\n if isinstance(s, six.string_types):\n # On PY2, shlex.split will fail with unicode types if there are\n # non-ascii characters in the string. So, we need to make sure we\n # invoke it with a str type, and then decode the resulting string back\n # to unicode to return it.\n return salt.utils.data.decode(\n shlex.split(salt.utils.stringutils.to_str(s), **kwargs)\n )\n else:\n return s\n",
"def _rvm_do(ruby, command, runas=None, cwd=None, env=None):\n return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations and gemsets with RVM, the Ruby Version Manager.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
import os
import logging
# Import salt libs
import salt.utils.args
from salt.exceptions import CommandExecutionError
# Import 3rd party libs
from salt.ext import six
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rvm.runas': None,
}
def _get_rvm_location(runas=None):
if runas:
runas_home = os.path.expanduser('~{0}'.format(runas))
rvmpath = '{0}/.rvm/bin/rvm'.format(runas_home)
if os.path.exists(rvmpath):
return [rvmpath]
return ['/usr/local/rvm/bin/rvm']
def _rvm(command, runas=None, cwd=None, env=None):
if runas is None:
runas = __salt__['config.option']('rvm.runas')
if not is_installed(runas):
return False
cmd = _get_rvm_location(runas) + command
ret = __salt__['cmd.run_all'](cmd,
runas=runas,
cwd=cwd,
python_shell=False,
env=env)
if ret['retcode'] == 0:
return ret['stdout']
return False
def _rvm_do(ruby, command, runas=None, cwd=None, env=None):
return _rvm([ruby or 'default', 'do'] + command, runas=runas, cwd=cwd, env=env)
def is_installed(runas=None):
'''
Check if RVM is installed.
CLI Example:
.. code-block:: bash
salt '*' rvm.is_installed
'''
try:
return __salt__['cmd.has_exec'](_get_rvm_location(runas)[0])
except IndexError:
return False
def install(runas=None):
'''
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
'''
# RVM dependencies on Ubuntu 10.04:
# bash coreutils gzip bzip2 gawk sed curl git-core subversion
installer = 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer'
ret = __salt__['cmd.run_all'](
# the RVM installer automatically does a multi-user install when it is
# invoked with root privileges
'curl -Ls {installer} | bash -s stable'.format(installer=installer),
runas=runas,
python_shell=True
)
if ret['retcode'] > 0:
msg = 'Error encountered while downloading the RVM installer'
if ret['stderr']:
msg += '. stderr follows:\n\n' + ret['stderr']
raise CommandExecutionError(msg)
return True
def install_ruby(ruby, runas=None, opts=None, env=None):
'''
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to set for the install command. Useful for exporting compilation
flags such as RUBY_CONFIGURE_OPTS
opts
List of options to pass to the RVM installer (ie -C, --patch, etc)
CLI Example:
.. code-block:: bash
salt '*' rvm.install_ruby 1.9.3-p385
'''
# MRI/RBX/REE dependencies for Ubuntu 10.04:
# build-essential openssl libreadline6 libreadline6-dev curl
# git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0
# libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev autoconf libc6-dev
# libncurses5-dev automake libtool bison subversion ruby
if opts is None:
opts = []
if runas and runas != 'root':
_rvm(['autolibs', 'disable', ruby] + opts, runas=runas)
opts.append('--disable-binary')
return _rvm(['install', ruby] + opts, runas=runas, env=env)
def reinstall_ruby(ruby, runas=None, env=None):
'''
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.reinstall_ruby 1.9.3-p385
'''
return _rvm(['reinstall', ruby], runas=runas, env=env)
def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile(r'^[= ]([*> ]) ([^- ]+)-([^ ]+) \[ (.*) \]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([
match.group(2), match.group(3), match.group(1) == '*'
])
return rubies
def set_default(ruby, runas=None):
'''
Set the default ruby
ruby
The version of ruby to make the default
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.set_default 2.0.0
'''
return _rvm(['alias', 'create', 'default', ruby], runas=runas)
def get(version='stable', runas=None):
'''
Update RVM
version : stable
Which version of RVM to install, (e.g. stable or head)
CLI Example:
.. code-block:: bash
salt '*' rvm.get
'''
return _rvm(['get', version], runas=runas)
def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
binaries : None
The names of the binaries to create wrappers for. When nothing is
given, wrappers for ruby, gem, rake, irb, rdoc, ri and testrb are
generated.
CLI Example:
.. code-block:: bash
salt '*' rvm.wrapper <ruby_string> <wrapper_prefix>
'''
cmd = ['wrapper', ruby_string, wrapper_prefix]
cmd.extend(binaries)
return _rvm(cmd, runas=runas)
def rubygems(ruby, version, runas=None):
'''
Installs a specific rubygems version in the given ruby
ruby
The ruby for which to install rubygems
version
The version of rubygems to install, or 'remove' to use the version that
ships with 1.9
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.rubygems 2.0.0 1.8.24
'''
return _rvm_do(ruby, ['rubygems', version], runas=runas)
def gemset_create(ruby, gemset, runas=None):
'''
Creates a gemset.
ruby
The ruby version for which to create the gemset
gemset
The name of the gemset to create
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_create 2.0.0 foobar
'''
return _rvm_do(ruby, ['rvm', 'gemset', 'create', gemset], runas=runas)
def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list
'''
gemsets = []
output = _rvm_do(ruby, ['rvm', 'gemset', 'list'], runas=runas)
if output:
regex = re.compile('^ ([^ ]+)')
for line in output.splitlines():
match = regex.match(line)
if match:
gemsets.append(match.group(1))
return gemsets
def gemset_delete(ruby, gemset, runas=None):
'''
Delete a gemset
ruby
The ruby version to which the gemset belongs
gemset
The gemset to delete
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_delete 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'delete', gemset],
runas=runas)
def gemset_empty(ruby, gemset, runas=None):
'''
Remove all gems from a gemset.
ruby
The ruby version to which the gemset belongs
gemset
The gemset to empty
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_empty 2.0.0 foobar
'''
return _rvm_do(ruby,
['rvm', '--force', 'gemset', 'empty', gemset],
runas=runas)
def gemset_copy(source, destination, runas=None):
'''
Copy all gems from one gemset to another.
source
The name of the gemset to copy, complete with ruby version
destination
The destination gemset
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_copy foobar bazquo
'''
return _rvm(['gemset', 'copy', source, destination], runas=runas)
def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.gemset_list_all
'''
gemsets = {}
current_ruby = None
output = _rvm_do('default', ['rvm', 'gemset', 'list_all'], runas=runas)
if output:
gems_regex = re.compile('^ ([^ ]+)')
gemset_regex = re.compile('^gemsets for ([^ ]+)')
for line in output.splitlines():
match = gemset_regex.match(line)
if match:
current_ruby = match.group(1)
gemsets[current_ruby] = []
match = gems_regex.match(line)
if match:
gemsets[current_ruby].append(match.group(1))
return gemsets
|
saltstack/salt
|
doc/_ext/saltdomain.py
|
LiterateCoding.parse_file
|
python
|
def parse_file(self, fpath):
'''
Read a file on the file system (relative to salt's base project dir)
:returns: A file-like object.
:raises IOError: If the file cannot be found or read.
'''
sdir = os.path.abspath(os.path.join(os.path.dirname(salt.__file__),
os.pardir))
with open(os.path.join(sdir, fpath), 'rb') as f:
return f.readlines()
|
Read a file on the file system (relative to salt's base project dir)
:returns: A file-like object.
:raises IOError: If the file cannot be found or read.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/doc/_ext/saltdomain.py#L40-L50
| null |
class LiterateCoding(Directive):
'''
Auto-doc SLS files using literate-style comment/code separation
'''
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
def parse_lit(self, lines):
'''
Parse a string line-by-line delineating comments and code
:returns: An tuple of boolean/list-of-string pairs. True designates a
comment; False designates code.
'''
comment_char = '#' # TODO: move this into a directive option
comment = re.compile(r'^\s*{0}[ \n]'.format(comment_char))
section_test = lambda val: bool(comment.match(val))
sections = []
for is_doc, group in itertools.groupby(lines, section_test):
if is_doc:
text = [comment.sub('', i).rstrip('\r\n') for i in group]
else:
text = [i.rstrip('\r\n') for i in group]
sections.append((is_doc, text))
return sections
def run(self):
try:
lines = self.parse_lit(self.parse_file(self.arguments[0]))
except IOError as exc:
document = self.state.document
return [document.reporter.warning(str(exc), line=self.lineno)]
node = nodes.container()
node['classes'] = ['lit-container']
node.document = self.state.document
enum = nodes.enumerated_list()
enum['classes'] = ['lit-docs']
node.append(enum)
# make first list item
list_item = nodes.list_item()
list_item['classes'] = ['lit-item']
for is_doc, line in lines:
if is_doc and line == ['']:
continue
section = nodes.section()
if is_doc:
section['classes'] = ['lit-annotation']
nested_parse_with_titles(self.state, ViewList(line), section)
else:
section['classes'] = ['lit-content']
code = '\n'.join(line)
literal = nodes.literal_block(code, code)
literal['language'] = 'yaml'
set_source_info(self, literal)
section.append(literal)
list_item.append(section)
# If we have a pair of annotation/content items, append the list
# item and create a new list item
if len(list_item.children) == 2:
enum.append(list_item)
list_item = nodes.list_item()
list_item['classes'] = ['lit-item']
# Non-semantic div for styling
bg = nodes.container()
bg['classes'] = ['lit-background']
node.append(bg)
return [node]
|
saltstack/salt
|
doc/_ext/saltdomain.py
|
LiterateCoding.parse_lit
|
python
|
def parse_lit(self, lines):
'''
Parse a string line-by-line delineating comments and code
:returns: An tuple of boolean/list-of-string pairs. True designates a
comment; False designates code.
'''
comment_char = '#' # TODO: move this into a directive option
comment = re.compile(r'^\s*{0}[ \n]'.format(comment_char))
section_test = lambda val: bool(comment.match(val))
sections = []
for is_doc, group in itertools.groupby(lines, section_test):
if is_doc:
text = [comment.sub('', i).rstrip('\r\n') for i in group]
else:
text = [i.rstrip('\r\n') for i in group]
sections.append((is_doc, text))
return sections
|
Parse a string line-by-line delineating comments and code
:returns: An tuple of boolean/list-of-string pairs. True designates a
comment; False designates code.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/doc/_ext/saltdomain.py#L52-L72
| null |
class LiterateCoding(Directive):
'''
Auto-doc SLS files using literate-style comment/code separation
'''
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
def parse_file(self, fpath):
'''
Read a file on the file system (relative to salt's base project dir)
:returns: A file-like object.
:raises IOError: If the file cannot be found or read.
'''
sdir = os.path.abspath(os.path.join(os.path.dirname(salt.__file__),
os.pardir))
with open(os.path.join(sdir, fpath), 'rb') as f:
return f.readlines()
def run(self):
try:
lines = self.parse_lit(self.parse_file(self.arguments[0]))
except IOError as exc:
document = self.state.document
return [document.reporter.warning(str(exc), line=self.lineno)]
node = nodes.container()
node['classes'] = ['lit-container']
node.document = self.state.document
enum = nodes.enumerated_list()
enum['classes'] = ['lit-docs']
node.append(enum)
# make first list item
list_item = nodes.list_item()
list_item['classes'] = ['lit-item']
for is_doc, line in lines:
if is_doc and line == ['']:
continue
section = nodes.section()
if is_doc:
section['classes'] = ['lit-annotation']
nested_parse_with_titles(self.state, ViewList(line), section)
else:
section['classes'] = ['lit-content']
code = '\n'.join(line)
literal = nodes.literal_block(code, code)
literal['language'] = 'yaml'
set_source_info(self, literal)
section.append(literal)
list_item.append(section)
# If we have a pair of annotation/content items, append the list
# item and create a new list item
if len(list_item.children) == 2:
enum.append(list_item)
list_item = nodes.list_item()
list_item['classes'] = ['lit-item']
# Non-semantic div for styling
bg = nodes.container()
bg['classes'] = ['lit-background']
node.append(bg)
return [node]
|
saltstack/salt
|
doc/_ext/saltdomain.py
|
LiterateFormula.parse_file
|
python
|
def parse_file(self, sls_path):
'''
Given a typical Salt SLS path (e.g.: apache.vhosts.standard), find the
file on the file system and parse it
'''
config = self.state.document.settings.env.config
formulas_dirs = config.formulas_dirs
fpath = sls_path.replace('.', '/')
name_options = (
'{0}.sls'.format(fpath),
os.path.join(fpath, 'init.sls')
)
paths = [os.path.join(fdir, fname)
for fname in name_options
for fdir in formulas_dirs]
for i in paths:
try:
with open(i, 'rb') as f:
return f.readlines()
except IOError:
pass
raise IOError("Could not find sls file '{0}'".format(sls_path))
|
Given a typical Salt SLS path (e.g.: apache.vhosts.standard), find the
file on the file system and parse it
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/doc/_ext/saltdomain.py#L134-L159
| null |
class LiterateFormula(LiterateCoding):
'''
Customizations to handle finding and parsing SLS files
'''
|
saltstack/salt
|
salt/matchers/compound_pillar_exact_match.py
|
mmatch
|
python
|
def mmatch(expr, delimiter, greedy, opts=None):
'''
Return the minions found by looking via pillar
'''
if not opts:
opts = __opts__
ckminions = salt.utils.minions.CkMinions(opts)
return ckminions._check_compound_minions(expr, delimiter, greedy,
pillar_exact=True)
|
Return the minions found by looking via pillar
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/compound_pillar_exact_match.py#L17-L26
|
[
"def _check_compound_minions(self,\n expr,\n delimiter,\n greedy,\n pillar_exact=False): # pylint: disable=unused-argument\n '''\n Return the minions found by looking via compound matcher\n '''\n if not isinstance(expr, six.string_types) and not isinstance(expr, (list, tuple)):\n log.error('Compound target that is neither string, list nor tuple')\n return {'minions': [], 'missing': []}\n minions = set(self._pki_minions())\n log.debug('minions: %s', minions)\n\n nodegroups = self.opts.get('nodegroups', {})\n\n if self.opts.get('minion_data_cache', False):\n ref = {'G': self._check_grain_minions,\n 'P': self._check_grain_pcre_minions,\n 'I': self._check_pillar_minions,\n 'J': self._check_pillar_pcre_minions,\n 'L': self._check_list_minions,\n 'N': None, # nodegroups should already be expanded\n 'S': self._check_ipcidr_minions,\n 'E': self._check_pcre_minions,\n 'R': self._all_minions}\n if pillar_exact:\n ref['I'] = self._check_pillar_exact_minions\n ref['J'] = self._check_pillar_exact_minions\n\n results = []\n unmatched = []\n opers = ['and', 'or', 'not', '(', ')']\n missing = []\n\n if isinstance(expr, six.string_types):\n words = expr.split()\n else:\n # we make a shallow copy in order to not affect the passed in arg\n words = expr[:]\n\n while words:\n word = words.pop(0)\n target_info = parse_target(word)\n\n # Easy check first\n if word in opers:\n if results:\n if results[-1] == '(' and word in ('and', 'or'):\n log.error('Invalid beginning operator after \"(\": %s', word)\n return {'minions': [], 'missing': []}\n if word == 'not':\n if not results[-1] in ('&', '|', '('):\n results.append('&')\n results.append('(')\n results.append(six.text_type(set(minions)))\n results.append('-')\n unmatched.append('-')\n elif word == 'and':\n results.append('&')\n elif word == 'or':\n results.append('|')\n elif word == '(':\n results.append(word)\n unmatched.append(word)\n elif word == ')':\n if not unmatched or unmatched[-1] != '(':\n log.error('Invalid compound expr (unexpected '\n 'right parenthesis): %s',\n expr)\n return {'minions': [], 'missing': []}\n results.append(word)\n unmatched.pop()\n if unmatched and unmatched[-1] == '-':\n results.append(')')\n unmatched.pop()\n else: # Won't get here, unless oper is added\n log.error('Unhandled oper in compound expr: %s',\n expr)\n return {'minions': [], 'missing': []}\n else:\n # seq start with oper, fail\n if word == 'not':\n results.append('(')\n results.append(six.text_type(set(minions)))\n results.append('-')\n unmatched.append('-')\n elif word == '(':\n results.append(word)\n unmatched.append(word)\n else:\n log.error(\n 'Expression may begin with'\n ' binary operator: %s', word\n )\n return {'minions': [], 'missing': []}\n\n elif target_info and target_info['engine']:\n if 'N' == target_info['engine']:\n # if we encounter a node group, just evaluate it in-place\n decomposed = nodegroup_comp(target_info['pattern'], nodegroups)\n if decomposed:\n words = decomposed + words\n continue\n\n engine = ref.get(target_info['engine'])\n if not engine:\n # If an unknown engine is called at any time, fail out\n log.error(\n 'Unrecognized target engine \"%s\" for'\n ' target expression \"%s\"',\n target_info['engine'],\n word,\n )\n return {'minions': [], 'missing': []}\n\n engine_args = [target_info['pattern']]\n if target_info['engine'] in ('G', 'P', 'I', 'J'):\n engine_args.append(target_info['delimiter'] or ':')\n engine_args.append(greedy)\n\n # ignore missing minions for lists if we exclude them with\n # a 'not'\n if 'L' == target_info['engine']:\n engine_args.append(results and results[-1] == '-')\n _results = engine(*engine_args)\n results.append(six.text_type(set(_results['minions'])))\n missing.extend(_results['missing'])\n if unmatched and unmatched[-1] == '-':\n results.append(')')\n unmatched.pop()\n\n else:\n # The match is not explicitly defined, evaluate as a glob\n _results = self._check_glob_minions(word, True)\n results.append(six.text_type(set(_results['minions'])))\n if unmatched and unmatched[-1] == '-':\n results.append(')')\n unmatched.pop()\n\n # Add a closing ')' for each item left in unmatched\n results.extend([')' for item in unmatched])\n\n results = ' '.join(results)\n log.debug('Evaluating final compound matching expr: %s',\n results)\n try:\n minions = list(eval(results)) # pylint: disable=W0123\n return {'minions': minions, 'missing': missing}\n except Exception:\n log.error('Invalid compound target: %s', expr)\n return {'minions': [], 'missing': []}\n\n return {'minions': list(minions),\n 'missing': []}\n"
] |
# -*- coding: utf-8 -*-
'''
This is the default pillar exact matcher for compound matches.
There is no minion-side equivalent for this, so consequently there is no ``match()``
function below, only an ``mmatch()``
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.utils.minions # pylint: disable=3rd-party-module-not-gated
log = logging.getLogger(__name__)
|
saltstack/salt
|
salt/modules/sysfs.py
|
attr
|
python
|
def attr(key, value=None):
'''
Access/write a SysFS attribute.
If the attribute is a symlink, it's destination is returned
:return: value or bool
CLI example:
.. code-block:: bash
salt '*' sysfs.attr block/sda/queue/logical_block_size
'''
key = target(key)
if key is False:
return False
elif os.path.isdir(key):
return key
elif value is not None:
return write(key, value)
else:
return read(key)
|
Access/write a SysFS attribute.
If the attribute is a symlink, it's destination is returned
:return: value or bool
CLI example:
.. code-block:: bash
salt '*' sysfs.attr block/sda/queue/logical_block_size
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysfs.py#L32-L53
|
[
"def target(key, full=True):\n '''\n Return the basename of a SysFS key path\n\n :param key: the location to resolve within SysFS\n :param full: full path instead of basename\n\n :return: fullpath or basename of path\n\n CLI example:\n .. code-block:: bash\n\n salt '*' sysfs.read class/ttyS0\n\n '''\n if not key.startswith('/sys'):\n key = os.path.join('/sys', key)\n key = os.path.realpath(key)\n\n if not os.path.exists(key):\n log.debug('Unkown SysFS key %s', key)\n return False\n elif full:\n return key\n else:\n return os.path.basename(key)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for interfacing with SysFS
.. seealso:: https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt
.. versionadded:: 2016.3.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
import stat
# Import Salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on Linux
'''
return salt.utils.platform.is_linux()
def write(key, value):
'''
Write a SysFS attribute/action
CLI example:
.. code-block:: bash
salt '*' sysfs.write devices/system/cpu/cpu0/cpufreq/scaling_governor 'performance'
'''
try:
key = target(key)
log.trace('Writing %s to %s', value, key)
with salt.utils.files.fopen(key, 'w') as twriter:
twriter.write(
salt.utils.stringutils.to_str('{0}\n'.format(value))
)
return True
except Exception:
return False
def read(key, root=''):
'''
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
'''
if not isinstance(key, six.string_types):
res = {}
for akey in key:
ares = read(os.path.join(root, akey))
if ares is not False:
res[akey] = ares
return res
key = target(os.path.join(root, key))
if key is False:
return False
elif os.path.isdir(key):
keys = interfaces(key)
result = {}
for subkey in keys['r'] + keys['rw']:
subval = read(os.path.join(key, subkey))
if subval is not False:
subkeys = subkey.split('/')
subkey = subkeys.pop()
subresult = result
if subkeys:
for skey in subkeys:
if skey not in subresult:
subresult[skey] = {}
subresult = subresult[skey]
subresult[subkey] = subval
return result
else:
try:
log.trace('Reading %s...', key)
# Certain things in SysFS are pipes 'n such.
# This opens it non-blocking, which prevents indefinite blocking
with os.fdopen(os.open(key, os.O_RDONLY | os.O_NONBLOCK)) as treader:
# alternative method for the same idea, but only works for completely empty pipes
# treader = select.select([treader], [], [], 1)[0][0]
val = treader.read().strip()
if not val:
return False
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
return val
except Exception:
return False
def target(key, full=True):
'''
Return the basename of a SysFS key path
:param key: the location to resolve within SysFS
:param full: full path instead of basename
:return: fullpath or basename of path
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/ttyS0
'''
if not key.startswith('/sys'):
key = os.path.join('/sys', key)
key = os.path.realpath(key)
if not os.path.exists(key):
log.debug('Unkown SysFS key %s', key)
return False
elif full:
return key
else:
return os.path.basename(key)
def interfaces(root):
'''
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
{
"r": [
"state",
"partial_stripes_expensive",
"writeback_rate_debug",
"stripe_size",
"dirty_data",
"stats_total/cache_hits",
"stats_total/cache_bypass_misses",
"stats_total/bypassed",
"stats_total/cache_readaheads",
"stats_total/cache_hit_ratio",
"stats_total/cache_miss_collisions",
"stats_total/cache_misses",
"stats_total/cache_bypass_hits",
],
"rw": [
"writeback_rate",
"writeback_rate_update_seconds",
"cache_mode",
"writeback_delay",
"label",
"writeback_running",
"writeback_metadata",
"running",
"writeback_rate_p_term_inverse",
"sequential_cutoff",
"writeback_percent",
"writeback_rate_d_term",
"readahead"
],
"w": [
"stop",
"clear_stats",
"attach",
"detach"
]
}
.. note::
* 'r' interfaces are read-only
* 'w' interfaces are write-only (e.g. actions)
* 'rw' are interfaces that can both be read or written
'''
root = target(root)
if root is False or not os.path.isdir(root):
log.error('SysFS %s not a dir', root)
return False
readwrites = []
reads = []
writes = []
for path, _, files in salt.utils.path.os_walk(root, followlinks=False):
for afile in files:
canpath = os.path.join(path, afile)
if not os.path.isfile(canpath):
continue
stat_mode = os.stat(canpath).st_mode
is_r = bool(stat.S_IRUSR & stat_mode)
is_w = bool(stat.S_IWUSR & stat_mode)
relpath = os.path.relpath(canpath, root)
if is_w:
if is_r:
readwrites.append(relpath)
else:
writes.append(relpath)
elif is_r:
reads.append(relpath)
else:
log.warning('Unable to find any interfaces in %s', canpath)
return {
'r': reads,
'w': writes,
'rw': readwrites
}
|
saltstack/salt
|
salt/modules/sysfs.py
|
write
|
python
|
def write(key, value):
'''
Write a SysFS attribute/action
CLI example:
.. code-block:: bash
salt '*' sysfs.write devices/system/cpu/cpu0/cpufreq/scaling_governor 'performance'
'''
try:
key = target(key)
log.trace('Writing %s to %s', value, key)
with salt.utils.files.fopen(key, 'w') as twriter:
twriter.write(
salt.utils.stringutils.to_str('{0}\n'.format(value))
)
return True
except Exception:
return False
|
Write a SysFS attribute/action
CLI example:
.. code-block:: bash
salt '*' sysfs.write devices/system/cpu/cpu0/cpufreq/scaling_governor 'performance'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysfs.py#L56-L74
|
[
"def target(key, full=True):\n '''\n Return the basename of a SysFS key path\n\n :param key: the location to resolve within SysFS\n :param full: full path instead of basename\n\n :return: fullpath or basename of path\n\n CLI example:\n .. code-block:: bash\n\n salt '*' sysfs.read class/ttyS0\n\n '''\n if not key.startswith('/sys'):\n key = os.path.join('/sys', key)\n key = os.path.realpath(key)\n\n if not os.path.exists(key):\n log.debug('Unkown SysFS key %s', key)\n return False\n elif full:\n return key\n else:\n return os.path.basename(key)\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n"
] |
# -*- coding: utf-8 -*-
'''
Module for interfacing with SysFS
.. seealso:: https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt
.. versionadded:: 2016.3.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
import stat
# Import Salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on Linux
'''
return salt.utils.platform.is_linux()
def attr(key, value=None):
'''
Access/write a SysFS attribute.
If the attribute is a symlink, it's destination is returned
:return: value or bool
CLI example:
.. code-block:: bash
salt '*' sysfs.attr block/sda/queue/logical_block_size
'''
key = target(key)
if key is False:
return False
elif os.path.isdir(key):
return key
elif value is not None:
return write(key, value)
else:
return read(key)
def read(key, root=''):
'''
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
'''
if not isinstance(key, six.string_types):
res = {}
for akey in key:
ares = read(os.path.join(root, akey))
if ares is not False:
res[akey] = ares
return res
key = target(os.path.join(root, key))
if key is False:
return False
elif os.path.isdir(key):
keys = interfaces(key)
result = {}
for subkey in keys['r'] + keys['rw']:
subval = read(os.path.join(key, subkey))
if subval is not False:
subkeys = subkey.split('/')
subkey = subkeys.pop()
subresult = result
if subkeys:
for skey in subkeys:
if skey not in subresult:
subresult[skey] = {}
subresult = subresult[skey]
subresult[subkey] = subval
return result
else:
try:
log.trace('Reading %s...', key)
# Certain things in SysFS are pipes 'n such.
# This opens it non-blocking, which prevents indefinite blocking
with os.fdopen(os.open(key, os.O_RDONLY | os.O_NONBLOCK)) as treader:
# alternative method for the same idea, but only works for completely empty pipes
# treader = select.select([treader], [], [], 1)[0][0]
val = treader.read().strip()
if not val:
return False
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
return val
except Exception:
return False
def target(key, full=True):
'''
Return the basename of a SysFS key path
:param key: the location to resolve within SysFS
:param full: full path instead of basename
:return: fullpath or basename of path
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/ttyS0
'''
if not key.startswith('/sys'):
key = os.path.join('/sys', key)
key = os.path.realpath(key)
if not os.path.exists(key):
log.debug('Unkown SysFS key %s', key)
return False
elif full:
return key
else:
return os.path.basename(key)
def interfaces(root):
'''
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
{
"r": [
"state",
"partial_stripes_expensive",
"writeback_rate_debug",
"stripe_size",
"dirty_data",
"stats_total/cache_hits",
"stats_total/cache_bypass_misses",
"stats_total/bypassed",
"stats_total/cache_readaheads",
"stats_total/cache_hit_ratio",
"stats_total/cache_miss_collisions",
"stats_total/cache_misses",
"stats_total/cache_bypass_hits",
],
"rw": [
"writeback_rate",
"writeback_rate_update_seconds",
"cache_mode",
"writeback_delay",
"label",
"writeback_running",
"writeback_metadata",
"running",
"writeback_rate_p_term_inverse",
"sequential_cutoff",
"writeback_percent",
"writeback_rate_d_term",
"readahead"
],
"w": [
"stop",
"clear_stats",
"attach",
"detach"
]
}
.. note::
* 'r' interfaces are read-only
* 'w' interfaces are write-only (e.g. actions)
* 'rw' are interfaces that can both be read or written
'''
root = target(root)
if root is False or not os.path.isdir(root):
log.error('SysFS %s not a dir', root)
return False
readwrites = []
reads = []
writes = []
for path, _, files in salt.utils.path.os_walk(root, followlinks=False):
for afile in files:
canpath = os.path.join(path, afile)
if not os.path.isfile(canpath):
continue
stat_mode = os.stat(canpath).st_mode
is_r = bool(stat.S_IRUSR & stat_mode)
is_w = bool(stat.S_IWUSR & stat_mode)
relpath = os.path.relpath(canpath, root)
if is_w:
if is_r:
readwrites.append(relpath)
else:
writes.append(relpath)
elif is_r:
reads.append(relpath)
else:
log.warning('Unable to find any interfaces in %s', canpath)
return {
'r': reads,
'w': writes,
'rw': readwrites
}
|
saltstack/salt
|
salt/modules/sysfs.py
|
read
|
python
|
def read(key, root=''):
'''
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
'''
if not isinstance(key, six.string_types):
res = {}
for akey in key:
ares = read(os.path.join(root, akey))
if ares is not False:
res[akey] = ares
return res
key = target(os.path.join(root, key))
if key is False:
return False
elif os.path.isdir(key):
keys = interfaces(key)
result = {}
for subkey in keys['r'] + keys['rw']:
subval = read(os.path.join(key, subkey))
if subval is not False:
subkeys = subkey.split('/')
subkey = subkeys.pop()
subresult = result
if subkeys:
for skey in subkeys:
if skey not in subresult:
subresult[skey] = {}
subresult = subresult[skey]
subresult[subkey] = subval
return result
else:
try:
log.trace('Reading %s...', key)
# Certain things in SysFS are pipes 'n such.
# This opens it non-blocking, which prevents indefinite blocking
with os.fdopen(os.open(key, os.O_RDONLY | os.O_NONBLOCK)) as treader:
# alternative method for the same idea, but only works for completely empty pipes
# treader = select.select([treader], [], [], 1)[0][0]
val = treader.read().strip()
if not val:
return False
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
return val
except Exception:
return False
|
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysfs.py#L77-L139
|
[
"def read(key, root=''):\n '''\n Read from SysFS\n\n :param key: file or path in SysFS; if key is a list then root will be prefixed on each key\n\n :return: the full (tree of) SysFS attributes under key\n\n CLI example:\n .. code-block:: bash\n\n salt '*' sysfs.read class/net/em1/statistics\n '''\n\n if not isinstance(key, six.string_types):\n res = {}\n for akey in key:\n ares = read(os.path.join(root, akey))\n if ares is not False:\n res[akey] = ares\n return res\n\n key = target(os.path.join(root, key))\n if key is False:\n return False\n elif os.path.isdir(key):\n keys = interfaces(key)\n result = {}\n for subkey in keys['r'] + keys['rw']:\n subval = read(os.path.join(key, subkey))\n if subval is not False:\n subkeys = subkey.split('/')\n subkey = subkeys.pop()\n subresult = result\n if subkeys:\n for skey in subkeys:\n if skey not in subresult:\n subresult[skey] = {}\n subresult = subresult[skey]\n subresult[subkey] = subval\n return result\n else:\n try:\n log.trace('Reading %s...', key)\n\n # Certain things in SysFS are pipes 'n such.\n # This opens it non-blocking, which prevents indefinite blocking\n with os.fdopen(os.open(key, os.O_RDONLY | os.O_NONBLOCK)) as treader:\n # alternative method for the same idea, but only works for completely empty pipes\n # treader = select.select([treader], [], [], 1)[0][0]\n val = treader.read().strip()\n if not val:\n return False\n try:\n val = int(val)\n except Exception:\n try:\n val = float(val)\n except Exception:\n pass\n return val\n except Exception:\n return False\n",
"def target(key, full=True):\n '''\n Return the basename of a SysFS key path\n\n :param key: the location to resolve within SysFS\n :param full: full path instead of basename\n\n :return: fullpath or basename of path\n\n CLI example:\n .. code-block:: bash\n\n salt '*' sysfs.read class/ttyS0\n\n '''\n if not key.startswith('/sys'):\n key = os.path.join('/sys', key)\n key = os.path.realpath(key)\n\n if not os.path.exists(key):\n log.debug('Unkown SysFS key %s', key)\n return False\n elif full:\n return key\n else:\n return os.path.basename(key)\n",
"def interfaces(root):\n '''\n Generate a dictionary with all available interfaces relative to root.\n Symlinks are not followed.\n\n CLI example:\n .. code-block:: bash\n\n salt '*' sysfs.interfaces block/bcache0/bcache\n\n Output example:\n .. code-block:: json\n\n {\n \"r\": [\n \"state\",\n \"partial_stripes_expensive\",\n \"writeback_rate_debug\",\n \"stripe_size\",\n \"dirty_data\",\n \"stats_total/cache_hits\",\n \"stats_total/cache_bypass_misses\",\n \"stats_total/bypassed\",\n \"stats_total/cache_readaheads\",\n \"stats_total/cache_hit_ratio\",\n \"stats_total/cache_miss_collisions\",\n \"stats_total/cache_misses\",\n \"stats_total/cache_bypass_hits\",\n ],\n \"rw\": [\n \"writeback_rate\",\n \"writeback_rate_update_seconds\",\n \"cache_mode\",\n \"writeback_delay\",\n \"label\",\n \"writeback_running\",\n \"writeback_metadata\",\n \"running\",\n \"writeback_rate_p_term_inverse\",\n \"sequential_cutoff\",\n \"writeback_percent\",\n \"writeback_rate_d_term\",\n \"readahead\"\n ],\n \"w\": [\n \"stop\",\n \"clear_stats\",\n \"attach\",\n \"detach\"\n ]\n }\n\n .. note::\n * 'r' interfaces are read-only\n * 'w' interfaces are write-only (e.g. actions)\n * 'rw' are interfaces that can both be read or written\n '''\n\n root = target(root)\n if root is False or not os.path.isdir(root):\n log.error('SysFS %s not a dir', root)\n return False\n\n readwrites = []\n reads = []\n writes = []\n\n for path, _, files in salt.utils.path.os_walk(root, followlinks=False):\n for afile in files:\n canpath = os.path.join(path, afile)\n\n if not os.path.isfile(canpath):\n continue\n\n stat_mode = os.stat(canpath).st_mode\n is_r = bool(stat.S_IRUSR & stat_mode)\n is_w = bool(stat.S_IWUSR & stat_mode)\n\n relpath = os.path.relpath(canpath, root)\n if is_w:\n if is_r:\n readwrites.append(relpath)\n else:\n writes.append(relpath)\n elif is_r:\n reads.append(relpath)\n else:\n log.warning('Unable to find any interfaces in %s', canpath)\n\n return {\n 'r': reads,\n 'w': writes,\n 'rw': readwrites\n }\n"
] |
# -*- coding: utf-8 -*-
'''
Module for interfacing with SysFS
.. seealso:: https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt
.. versionadded:: 2016.3.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
import stat
# Import Salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on Linux
'''
return salt.utils.platform.is_linux()
def attr(key, value=None):
'''
Access/write a SysFS attribute.
If the attribute is a symlink, it's destination is returned
:return: value or bool
CLI example:
.. code-block:: bash
salt '*' sysfs.attr block/sda/queue/logical_block_size
'''
key = target(key)
if key is False:
return False
elif os.path.isdir(key):
return key
elif value is not None:
return write(key, value)
else:
return read(key)
def write(key, value):
'''
Write a SysFS attribute/action
CLI example:
.. code-block:: bash
salt '*' sysfs.write devices/system/cpu/cpu0/cpufreq/scaling_governor 'performance'
'''
try:
key = target(key)
log.trace('Writing %s to %s', value, key)
with salt.utils.files.fopen(key, 'w') as twriter:
twriter.write(
salt.utils.stringutils.to_str('{0}\n'.format(value))
)
return True
except Exception:
return False
def target(key, full=True):
'''
Return the basename of a SysFS key path
:param key: the location to resolve within SysFS
:param full: full path instead of basename
:return: fullpath or basename of path
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/ttyS0
'''
if not key.startswith('/sys'):
key = os.path.join('/sys', key)
key = os.path.realpath(key)
if not os.path.exists(key):
log.debug('Unkown SysFS key %s', key)
return False
elif full:
return key
else:
return os.path.basename(key)
def interfaces(root):
'''
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
{
"r": [
"state",
"partial_stripes_expensive",
"writeback_rate_debug",
"stripe_size",
"dirty_data",
"stats_total/cache_hits",
"stats_total/cache_bypass_misses",
"stats_total/bypassed",
"stats_total/cache_readaheads",
"stats_total/cache_hit_ratio",
"stats_total/cache_miss_collisions",
"stats_total/cache_misses",
"stats_total/cache_bypass_hits",
],
"rw": [
"writeback_rate",
"writeback_rate_update_seconds",
"cache_mode",
"writeback_delay",
"label",
"writeback_running",
"writeback_metadata",
"running",
"writeback_rate_p_term_inverse",
"sequential_cutoff",
"writeback_percent",
"writeback_rate_d_term",
"readahead"
],
"w": [
"stop",
"clear_stats",
"attach",
"detach"
]
}
.. note::
* 'r' interfaces are read-only
* 'w' interfaces are write-only (e.g. actions)
* 'rw' are interfaces that can both be read or written
'''
root = target(root)
if root is False or not os.path.isdir(root):
log.error('SysFS %s not a dir', root)
return False
readwrites = []
reads = []
writes = []
for path, _, files in salt.utils.path.os_walk(root, followlinks=False):
for afile in files:
canpath = os.path.join(path, afile)
if not os.path.isfile(canpath):
continue
stat_mode = os.stat(canpath).st_mode
is_r = bool(stat.S_IRUSR & stat_mode)
is_w = bool(stat.S_IWUSR & stat_mode)
relpath = os.path.relpath(canpath, root)
if is_w:
if is_r:
readwrites.append(relpath)
else:
writes.append(relpath)
elif is_r:
reads.append(relpath)
else:
log.warning('Unable to find any interfaces in %s', canpath)
return {
'r': reads,
'w': writes,
'rw': readwrites
}
|
saltstack/salt
|
salt/modules/sysfs.py
|
target
|
python
|
def target(key, full=True):
'''
Return the basename of a SysFS key path
:param key: the location to resolve within SysFS
:param full: full path instead of basename
:return: fullpath or basename of path
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/ttyS0
'''
if not key.startswith('/sys'):
key = os.path.join('/sys', key)
key = os.path.realpath(key)
if not os.path.exists(key):
log.debug('Unkown SysFS key %s', key)
return False
elif full:
return key
else:
return os.path.basename(key)
|
Return the basename of a SysFS key path
:param key: the location to resolve within SysFS
:param full: full path instead of basename
:return: fullpath or basename of path
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/ttyS0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysfs.py#L142-L167
| null |
# -*- coding: utf-8 -*-
'''
Module for interfacing with SysFS
.. seealso:: https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt
.. versionadded:: 2016.3.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
import stat
# Import Salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on Linux
'''
return salt.utils.platform.is_linux()
def attr(key, value=None):
'''
Access/write a SysFS attribute.
If the attribute is a symlink, it's destination is returned
:return: value or bool
CLI example:
.. code-block:: bash
salt '*' sysfs.attr block/sda/queue/logical_block_size
'''
key = target(key)
if key is False:
return False
elif os.path.isdir(key):
return key
elif value is not None:
return write(key, value)
else:
return read(key)
def write(key, value):
'''
Write a SysFS attribute/action
CLI example:
.. code-block:: bash
salt '*' sysfs.write devices/system/cpu/cpu0/cpufreq/scaling_governor 'performance'
'''
try:
key = target(key)
log.trace('Writing %s to %s', value, key)
with salt.utils.files.fopen(key, 'w') as twriter:
twriter.write(
salt.utils.stringutils.to_str('{0}\n'.format(value))
)
return True
except Exception:
return False
def read(key, root=''):
'''
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
'''
if not isinstance(key, six.string_types):
res = {}
for akey in key:
ares = read(os.path.join(root, akey))
if ares is not False:
res[akey] = ares
return res
key = target(os.path.join(root, key))
if key is False:
return False
elif os.path.isdir(key):
keys = interfaces(key)
result = {}
for subkey in keys['r'] + keys['rw']:
subval = read(os.path.join(key, subkey))
if subval is not False:
subkeys = subkey.split('/')
subkey = subkeys.pop()
subresult = result
if subkeys:
for skey in subkeys:
if skey not in subresult:
subresult[skey] = {}
subresult = subresult[skey]
subresult[subkey] = subval
return result
else:
try:
log.trace('Reading %s...', key)
# Certain things in SysFS are pipes 'n such.
# This opens it non-blocking, which prevents indefinite blocking
with os.fdopen(os.open(key, os.O_RDONLY | os.O_NONBLOCK)) as treader:
# alternative method for the same idea, but only works for completely empty pipes
# treader = select.select([treader], [], [], 1)[0][0]
val = treader.read().strip()
if not val:
return False
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
return val
except Exception:
return False
def interfaces(root):
'''
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
{
"r": [
"state",
"partial_stripes_expensive",
"writeback_rate_debug",
"stripe_size",
"dirty_data",
"stats_total/cache_hits",
"stats_total/cache_bypass_misses",
"stats_total/bypassed",
"stats_total/cache_readaheads",
"stats_total/cache_hit_ratio",
"stats_total/cache_miss_collisions",
"stats_total/cache_misses",
"stats_total/cache_bypass_hits",
],
"rw": [
"writeback_rate",
"writeback_rate_update_seconds",
"cache_mode",
"writeback_delay",
"label",
"writeback_running",
"writeback_metadata",
"running",
"writeback_rate_p_term_inverse",
"sequential_cutoff",
"writeback_percent",
"writeback_rate_d_term",
"readahead"
],
"w": [
"stop",
"clear_stats",
"attach",
"detach"
]
}
.. note::
* 'r' interfaces are read-only
* 'w' interfaces are write-only (e.g. actions)
* 'rw' are interfaces that can both be read or written
'''
root = target(root)
if root is False or not os.path.isdir(root):
log.error('SysFS %s not a dir', root)
return False
readwrites = []
reads = []
writes = []
for path, _, files in salt.utils.path.os_walk(root, followlinks=False):
for afile in files:
canpath = os.path.join(path, afile)
if not os.path.isfile(canpath):
continue
stat_mode = os.stat(canpath).st_mode
is_r = bool(stat.S_IRUSR & stat_mode)
is_w = bool(stat.S_IWUSR & stat_mode)
relpath = os.path.relpath(canpath, root)
if is_w:
if is_r:
readwrites.append(relpath)
else:
writes.append(relpath)
elif is_r:
reads.append(relpath)
else:
log.warning('Unable to find any interfaces in %s', canpath)
return {
'r': reads,
'w': writes,
'rw': readwrites
}
|
saltstack/salt
|
salt/modules/sysfs.py
|
interfaces
|
python
|
def interfaces(root):
'''
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
{
"r": [
"state",
"partial_stripes_expensive",
"writeback_rate_debug",
"stripe_size",
"dirty_data",
"stats_total/cache_hits",
"stats_total/cache_bypass_misses",
"stats_total/bypassed",
"stats_total/cache_readaheads",
"stats_total/cache_hit_ratio",
"stats_total/cache_miss_collisions",
"stats_total/cache_misses",
"stats_total/cache_bypass_hits",
],
"rw": [
"writeback_rate",
"writeback_rate_update_seconds",
"cache_mode",
"writeback_delay",
"label",
"writeback_running",
"writeback_metadata",
"running",
"writeback_rate_p_term_inverse",
"sequential_cutoff",
"writeback_percent",
"writeback_rate_d_term",
"readahead"
],
"w": [
"stop",
"clear_stats",
"attach",
"detach"
]
}
.. note::
* 'r' interfaces are read-only
* 'w' interfaces are write-only (e.g. actions)
* 'rw' are interfaces that can both be read or written
'''
root = target(root)
if root is False or not os.path.isdir(root):
log.error('SysFS %s not a dir', root)
return False
readwrites = []
reads = []
writes = []
for path, _, files in salt.utils.path.os_walk(root, followlinks=False):
for afile in files:
canpath = os.path.join(path, afile)
if not os.path.isfile(canpath):
continue
stat_mode = os.stat(canpath).st_mode
is_r = bool(stat.S_IRUSR & stat_mode)
is_w = bool(stat.S_IWUSR & stat_mode)
relpath = os.path.relpath(canpath, root)
if is_w:
if is_r:
readwrites.append(relpath)
else:
writes.append(relpath)
elif is_r:
reads.append(relpath)
else:
log.warning('Unable to find any interfaces in %s', canpath)
return {
'r': reads,
'w': writes,
'rw': readwrites
}
|
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
{
"r": [
"state",
"partial_stripes_expensive",
"writeback_rate_debug",
"stripe_size",
"dirty_data",
"stats_total/cache_hits",
"stats_total/cache_bypass_misses",
"stats_total/bypassed",
"stats_total/cache_readaheads",
"stats_total/cache_hit_ratio",
"stats_total/cache_miss_collisions",
"stats_total/cache_misses",
"stats_total/cache_bypass_hits",
],
"rw": [
"writeback_rate",
"writeback_rate_update_seconds",
"cache_mode",
"writeback_delay",
"label",
"writeback_running",
"writeback_metadata",
"running",
"writeback_rate_p_term_inverse",
"sequential_cutoff",
"writeback_percent",
"writeback_rate_d_term",
"readahead"
],
"w": [
"stop",
"clear_stats",
"attach",
"detach"
]
}
.. note::
* 'r' interfaces are read-only
* 'w' interfaces are write-only (e.g. actions)
* 'rw' are interfaces that can both be read or written
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysfs.py#L170-L263
|
[
"def target(key, full=True):\n '''\n Return the basename of a SysFS key path\n\n :param key: the location to resolve within SysFS\n :param full: full path instead of basename\n\n :return: fullpath or basename of path\n\n CLI example:\n .. code-block:: bash\n\n salt '*' sysfs.read class/ttyS0\n\n '''\n if not key.startswith('/sys'):\n key = os.path.join('/sys', key)\n key = os.path.realpath(key)\n\n if not os.path.exists(key):\n log.debug('Unkown SysFS key %s', key)\n return False\n elif full:\n return key\n else:\n return os.path.basename(key)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for interfacing with SysFS
.. seealso:: https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt
.. versionadded:: 2016.3.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
import stat
# Import Salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on Linux
'''
return salt.utils.platform.is_linux()
def attr(key, value=None):
'''
Access/write a SysFS attribute.
If the attribute is a symlink, it's destination is returned
:return: value or bool
CLI example:
.. code-block:: bash
salt '*' sysfs.attr block/sda/queue/logical_block_size
'''
key = target(key)
if key is False:
return False
elif os.path.isdir(key):
return key
elif value is not None:
return write(key, value)
else:
return read(key)
def write(key, value):
'''
Write a SysFS attribute/action
CLI example:
.. code-block:: bash
salt '*' sysfs.write devices/system/cpu/cpu0/cpufreq/scaling_governor 'performance'
'''
try:
key = target(key)
log.trace('Writing %s to %s', value, key)
with salt.utils.files.fopen(key, 'w') as twriter:
twriter.write(
salt.utils.stringutils.to_str('{0}\n'.format(value))
)
return True
except Exception:
return False
def read(key, root=''):
'''
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
'''
if not isinstance(key, six.string_types):
res = {}
for akey in key:
ares = read(os.path.join(root, akey))
if ares is not False:
res[akey] = ares
return res
key = target(os.path.join(root, key))
if key is False:
return False
elif os.path.isdir(key):
keys = interfaces(key)
result = {}
for subkey in keys['r'] + keys['rw']:
subval = read(os.path.join(key, subkey))
if subval is not False:
subkeys = subkey.split('/')
subkey = subkeys.pop()
subresult = result
if subkeys:
for skey in subkeys:
if skey not in subresult:
subresult[skey] = {}
subresult = subresult[skey]
subresult[subkey] = subval
return result
else:
try:
log.trace('Reading %s...', key)
# Certain things in SysFS are pipes 'n such.
# This opens it non-blocking, which prevents indefinite blocking
with os.fdopen(os.open(key, os.O_RDONLY | os.O_NONBLOCK)) as treader:
# alternative method for the same idea, but only works for completely empty pipes
# treader = select.select([treader], [], [], 1)[0][0]
val = treader.read().strip()
if not val:
return False
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
return val
except Exception:
return False
def target(key, full=True):
'''
Return the basename of a SysFS key path
:param key: the location to resolve within SysFS
:param full: full path instead of basename
:return: fullpath or basename of path
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/ttyS0
'''
if not key.startswith('/sys'):
key = os.path.join('/sys', key)
key = os.path.realpath(key)
if not os.path.exists(key):
log.debug('Unkown SysFS key %s', key)
return False
elif full:
return key
else:
return os.path.basename(key)
|
saltstack/salt
|
salt/returners/librato_return.py
|
_get_librato
|
python
|
def _get_librato(ret=None):
'''
Return a Librato connection object.
'''
_options = _get_options(ret)
conn = librato.connect(
_options.get('email'),
_options.get('api_token'),
sanitizer=librato.sanitize_metric_name,
hostname=_options.get('api_url'))
log.info("Connected to librato.")
return conn
|
Return a Librato connection object.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/librato_return.py#L82-L94
|
[
"def _get_options(ret=None):\n '''\n Get the Librato options from salt.\n '''\n attrs = {'email': 'email',\n 'api_token': 'api_token',\n 'api_url': 'api_url'\n }\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n\n _options['api_url'] = _options.get('api_url', 'metrics-api.librato.com')\n\n log.debug('Retrieved Librato options: %s', _options)\n return _options\n"
] |
# -*- coding: utf-8 -*-
'''
Salt returner to return highstate stats to Librato
To enable this returner the minion will need the Librato
client importable on the Python path and the following
values configured in the minion or master config.
The Librato python client can be found at:
https://github.com/librato/python-librato
.. code-block:: yaml
librato.email: example@librato.com
librato.api_token: abc12345def
This return supports multi-dimension metrics for Librato. To enable
support for more metrics, the tags JSON object can be modified to include
other tags.
Adding EC2 Tags example:
If ec2_tags:region were desired within the tags for multi-dimension. The tags
could be modified to include the ec2 tags. Multiple dimensions are added simply
by adding more tags to the submission.
.. code-block:: python
pillar_data = __salt__['pillar.raw']()
q.add(metric.name, value, tags={'Name': ret['id'],'Region': pillar_data['ec2_tags']['Name']})
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
# Import third party libs
try:
import librato
HAS_LIBRATO = True
except ImportError:
HAS_LIBRATO = False
# Define the module's Virtual Name
__virtualname__ = 'librato'
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_LIBRATO:
return False, 'Could not import librato module; ' \
'librato python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the Librato options from salt.
'''
attrs = {'email': 'email',
'api_token': 'api_token',
'api_url': 'api_url'
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
_options['api_url'] = _options.get('api_url', 'metrics-api.librato.com')
log.debug('Retrieved Librato options: %s', _options)
return _options
def _calculate_runtimes(states):
results = {
'runtime': 0.00,
'num_failed_states': 0,
'num_passed_states': 0
}
for state, resultset in states.items():
if isinstance(resultset, dict) and 'duration' in resultset:
# Count the pass vs failures
if resultset['result']:
results['num_passed_states'] += 1
else:
results['num_failed_states'] += 1
# Count durations
results['runtime'] += resultset['duration']
log.debug('Parsed state metrics: %s', results)
return results
def returner(ret):
'''
Parse the return data and return metrics to Librato.
'''
librato_conn = _get_librato(ret)
q = librato_conn.new_queue()
if ret['fun'] == 'state.highstate':
log.debug('Found returned Highstate data.')
# Calculate the runtimes and number of failed states.
stats = _calculate_runtimes(ret['return'])
log.debug('Batching Metric retcode with %s', ret['retcode'])
q.add('saltstack.highstate.retcode',
ret['retcode'], tags={'Name': ret['id']})
log.debug(
'Batching Metric num_failed_jobs with %s',
stats['num_failed_states']
)
q.add('saltstack.highstate.failed_states',
stats['num_failed_states'], tags={'Name': ret['id']})
log.debug(
'Batching Metric num_passed_states with %s',
stats['num_passed_states']
)
q.add('saltstack.highstate.passed_states',
stats['num_passed_states'], tags={'Name': ret['id']})
log.debug('Batching Metric runtime with %s', stats['runtime'])
q.add('saltstack.highstate.runtime',
stats['runtime'], tags={'Name': ret['id']})
log.debug(
'Batching Metric runtime with %s',
stats['num_failed_states'] + stats['num_passed_states']
)
q.add('saltstack.highstate.total_states', stats[
'num_failed_states'] + stats['num_passed_states'], tags={'Name': ret['id']})
log.info('Sending metrics to Librato.')
q.submit()
|
saltstack/salt
|
salt/returners/librato_return.py
|
returner
|
python
|
def returner(ret):
'''
Parse the return data and return metrics to Librato.
'''
librato_conn = _get_librato(ret)
q = librato_conn.new_queue()
if ret['fun'] == 'state.highstate':
log.debug('Found returned Highstate data.')
# Calculate the runtimes and number of failed states.
stats = _calculate_runtimes(ret['return'])
log.debug('Batching Metric retcode with %s', ret['retcode'])
q.add('saltstack.highstate.retcode',
ret['retcode'], tags={'Name': ret['id']})
log.debug(
'Batching Metric num_failed_jobs with %s',
stats['num_failed_states']
)
q.add('saltstack.highstate.failed_states',
stats['num_failed_states'], tags={'Name': ret['id']})
log.debug(
'Batching Metric num_passed_states with %s',
stats['num_passed_states']
)
q.add('saltstack.highstate.passed_states',
stats['num_passed_states'], tags={'Name': ret['id']})
log.debug('Batching Metric runtime with %s', stats['runtime'])
q.add('saltstack.highstate.runtime',
stats['runtime'], tags={'Name': ret['id']})
log.debug(
'Batching Metric runtime with %s',
stats['num_failed_states'] + stats['num_passed_states']
)
q.add('saltstack.highstate.total_states', stats[
'num_failed_states'] + stats['num_passed_states'], tags={'Name': ret['id']})
log.info('Sending metrics to Librato.')
q.submit()
|
Parse the return data and return metrics to Librato.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/librato_return.py#L119-L161
|
[
"def _calculate_runtimes(states):\n results = {\n 'runtime': 0.00,\n 'num_failed_states': 0,\n 'num_passed_states': 0\n }\n\n for state, resultset in states.items():\n if isinstance(resultset, dict) and 'duration' in resultset:\n # Count the pass vs failures\n if resultset['result']:\n results['num_passed_states'] += 1\n else:\n results['num_failed_states'] += 1\n\n # Count durations\n results['runtime'] += resultset['duration']\n\n log.debug('Parsed state metrics: %s', results)\n return results\n",
"def _get_librato(ret=None):\n '''\n Return a Librato connection object.\n '''\n _options = _get_options(ret)\n\n conn = librato.connect(\n _options.get('email'),\n _options.get('api_token'),\n sanitizer=librato.sanitize_metric_name,\n hostname=_options.get('api_url'))\n log.info(\"Connected to librato.\")\n return conn\n"
] |
# -*- coding: utf-8 -*-
'''
Salt returner to return highstate stats to Librato
To enable this returner the minion will need the Librato
client importable on the Python path and the following
values configured in the minion or master config.
The Librato python client can be found at:
https://github.com/librato/python-librato
.. code-block:: yaml
librato.email: example@librato.com
librato.api_token: abc12345def
This return supports multi-dimension metrics for Librato. To enable
support for more metrics, the tags JSON object can be modified to include
other tags.
Adding EC2 Tags example:
If ec2_tags:region were desired within the tags for multi-dimension. The tags
could be modified to include the ec2 tags. Multiple dimensions are added simply
by adding more tags to the submission.
.. code-block:: python
pillar_data = __salt__['pillar.raw']()
q.add(metric.name, value, tags={'Name': ret['id'],'Region': pillar_data['ec2_tags']['Name']})
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
# Import third party libs
try:
import librato
HAS_LIBRATO = True
except ImportError:
HAS_LIBRATO = False
# Define the module's Virtual Name
__virtualname__ = 'librato'
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_LIBRATO:
return False, 'Could not import librato module; ' \
'librato python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the Librato options from salt.
'''
attrs = {'email': 'email',
'api_token': 'api_token',
'api_url': 'api_url'
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
_options['api_url'] = _options.get('api_url', 'metrics-api.librato.com')
log.debug('Retrieved Librato options: %s', _options)
return _options
def _get_librato(ret=None):
'''
Return a Librato connection object.
'''
_options = _get_options(ret)
conn = librato.connect(
_options.get('email'),
_options.get('api_token'),
sanitizer=librato.sanitize_metric_name,
hostname=_options.get('api_url'))
log.info("Connected to librato.")
return conn
def _calculate_runtimes(states):
results = {
'runtime': 0.00,
'num_failed_states': 0,
'num_passed_states': 0
}
for state, resultset in states.items():
if isinstance(resultset, dict) and 'duration' in resultset:
# Count the pass vs failures
if resultset['result']:
results['num_passed_states'] += 1
else:
results['num_failed_states'] += 1
# Count durations
results['runtime'] += resultset['duration']
log.debug('Parsed state metrics: %s', results)
return results
|
saltstack/salt
|
salt/states/keystone_endpoint.py
|
_common
|
python
|
def _common(ret, name, service_name, kwargs):
'''
Returns: tuple whose first element is a bool indicating success or failure
and the second element is either a ret dict for salt or an object
'''
if 'interface' not in kwargs and 'public_url' not in kwargs:
kwargs['interface'] = name
service = __salt__['keystoneng.service_get'](name_or_id=service_name)
if not service:
ret['comment'] = 'Cannot find service'
ret['result'] = False
return (False, ret)
filters = kwargs.copy()
filters.pop('enabled', None)
filters.pop('url', None)
filters['service_id'] = service.id
kwargs['service_name_or_id'] = service.id
endpoints = __salt__['keystoneng.endpoint_search'](filters=filters)
if len(endpoints) > 1:
ret['comment'] = "Multiple endpoints match criteria"
ret['result'] = False
return ret
endpoint = endpoints[0] if endpoints else None
return (True, endpoint)
|
Returns: tuple whose first element is a bool indicating success or failure
and the second element is either a ret dict for salt or an object
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_endpoint.py#L51-L77
| null |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Keystone Endpoints
==========================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions
Example States
.. code-block:: yaml
create endpoint:
keystone_endpoint.present:
- name: public
- url: https://example.org:9292
- region: RegionOne
- service_name: glance
destroy endpoint:
keystone_endpoint.absent:
- name: public
- url: https://example.org:9292
- region: RegionOne
- service_name: glance
create multiple endpoints:
keystone_endpoint.absent:
- names:
- public
- admin
- internal
- url: https://example.org:9292
- region: RegionOne
- service_name: glance
'''
from __future__ import absolute_import, unicode_literals, print_function
__virtualname__ = 'keystone_endpoint'
def __virtual__():
if 'keystoneng.endpoint_get' in __salt__:
return __virtualname__
return (False, 'The keystoneng execution module failed to load: shade python module is not available')
def present(name, service_name, auth=None, **kwargs):
'''
Ensure an endpoint exists and is up-to-date
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
enabled
Boolean to control if endpoint is enabled
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_clouds'](auth)
success, val = _, endpoint = _common(ret, name, service_name, kwargs)
if not success:
return val
if not endpoint:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Endpoint will be created.'
return ret
# NOTE(SamYaple): Endpoints are returned as a list which can contain
# several items depending on the options passed
endpoints = __salt__['keystoneng.endpoint_create'](**kwargs)
if len(endpoints) == 1:
ret['changes'] = endpoints[0]
else:
for i, endpoint in enumerate(endpoints):
ret['changes'][i] = endpoint
ret['comment'] = 'Created endpoint'
return ret
changes = __salt__['keystoneng.compare_changes'](endpoint, **kwargs)
if changes:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = changes
ret['comment'] = 'Endpoint will be updated.'
return ret
kwargs['endpoint_id'] = endpoint.id
__salt__['keystoneng.endpoint_update'](**kwargs)
ret['changes'].update(changes)
ret['comment'] = 'Updated endpoint'
return ret
def absent(name, service_name, auth=None, **kwargs):
'''
Ensure an endpoint does not exists
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
success, val = _, endpoint = _common(ret, name, service_name, kwargs)
if not success:
return val
if endpoint:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'id': endpoint.id}
ret['comment'] = 'Endpoint will be deleted.'
return ret
__salt__['keystoneng.endpoint_delete'](id=endpoint.id)
ret['changes']['id'] = endpoint.id
ret['comment'] = 'Deleted endpoint'
return ret
|
saltstack/salt
|
salt/states/keystone_endpoint.py
|
present
|
python
|
def present(name, service_name, auth=None, **kwargs):
'''
Ensure an endpoint exists and is up-to-date
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
enabled
Boolean to control if endpoint is enabled
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_clouds'](auth)
success, val = _, endpoint = _common(ret, name, service_name, kwargs)
if not success:
return val
if not endpoint:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Endpoint will be created.'
return ret
# NOTE(SamYaple): Endpoints are returned as a list which can contain
# several items depending on the options passed
endpoints = __salt__['keystoneng.endpoint_create'](**kwargs)
if len(endpoints) == 1:
ret['changes'] = endpoints[0]
else:
for i, endpoint in enumerate(endpoints):
ret['changes'][i] = endpoint
ret['comment'] = 'Created endpoint'
return ret
changes = __salt__['keystoneng.compare_changes'](endpoint, **kwargs)
if changes:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = changes
ret['comment'] = 'Endpoint will be updated.'
return ret
kwargs['endpoint_id'] = endpoint.id
__salt__['keystoneng.endpoint_update'](**kwargs)
ret['changes'].update(changes)
ret['comment'] = 'Updated endpoint'
return ret
|
Ensure an endpoint exists and is up-to-date
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
enabled
Boolean to control if endpoint is enabled
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_endpoint.py#L80-L143
|
[
"def _common(ret, name, service_name, kwargs):\n '''\n Returns: tuple whose first element is a bool indicating success or failure\n and the second element is either a ret dict for salt or an object\n '''\n if 'interface' not in kwargs and 'public_url' not in kwargs:\n kwargs['interface'] = name\n service = __salt__['keystoneng.service_get'](name_or_id=service_name)\n\n if not service:\n ret['comment'] = 'Cannot find service'\n ret['result'] = False\n return (False, ret)\n\n filters = kwargs.copy()\n filters.pop('enabled', None)\n filters.pop('url', None)\n filters['service_id'] = service.id\n kwargs['service_name_or_id'] = service.id\n endpoints = __salt__['keystoneng.endpoint_search'](filters=filters)\n\n if len(endpoints) > 1:\n ret['comment'] = \"Multiple endpoints match criteria\"\n ret['result'] = False\n return ret\n endpoint = endpoints[0] if endpoints else None\n return (True, endpoint)\n"
] |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Keystone Endpoints
==========================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions
Example States
.. code-block:: yaml
create endpoint:
keystone_endpoint.present:
- name: public
- url: https://example.org:9292
- region: RegionOne
- service_name: glance
destroy endpoint:
keystone_endpoint.absent:
- name: public
- url: https://example.org:9292
- region: RegionOne
- service_name: glance
create multiple endpoints:
keystone_endpoint.absent:
- names:
- public
- admin
- internal
- url: https://example.org:9292
- region: RegionOne
- service_name: glance
'''
from __future__ import absolute_import, unicode_literals, print_function
__virtualname__ = 'keystone_endpoint'
def __virtual__():
if 'keystoneng.endpoint_get' in __salt__:
return __virtualname__
return (False, 'The keystoneng execution module failed to load: shade python module is not available')
def _common(ret, name, service_name, kwargs):
'''
Returns: tuple whose first element is a bool indicating success or failure
and the second element is either a ret dict for salt or an object
'''
if 'interface' not in kwargs and 'public_url' not in kwargs:
kwargs['interface'] = name
service = __salt__['keystoneng.service_get'](name_or_id=service_name)
if not service:
ret['comment'] = 'Cannot find service'
ret['result'] = False
return (False, ret)
filters = kwargs.copy()
filters.pop('enabled', None)
filters.pop('url', None)
filters['service_id'] = service.id
kwargs['service_name_or_id'] = service.id
endpoints = __salt__['keystoneng.endpoint_search'](filters=filters)
if len(endpoints) > 1:
ret['comment'] = "Multiple endpoints match criteria"
ret['result'] = False
return ret
endpoint = endpoints[0] if endpoints else None
return (True, endpoint)
def absent(name, service_name, auth=None, **kwargs):
'''
Ensure an endpoint does not exists
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
success, val = _, endpoint = _common(ret, name, service_name, kwargs)
if not success:
return val
if endpoint:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'id': endpoint.id}
ret['comment'] = 'Endpoint will be deleted.'
return ret
__salt__['keystoneng.endpoint_delete'](id=endpoint.id)
ret['changes']['id'] = endpoint.id
ret['comment'] = 'Deleted endpoint'
return ret
|
saltstack/salt
|
salt/states/keystone_endpoint.py
|
absent
|
python
|
def absent(name, service_name, auth=None, **kwargs):
'''
Ensure an endpoint does not exists
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
success, val = _, endpoint = _common(ret, name, service_name, kwargs)
if not success:
return val
if endpoint:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'id': endpoint.id}
ret['comment'] = 'Endpoint will be deleted.'
return ret
__salt__['keystoneng.endpoint_delete'](id=endpoint.id)
ret['changes']['id'] = endpoint.id
ret['comment'] = 'Deleted endpoint'
return ret
|
Ensure an endpoint does not exists
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_endpoint.py#L146-L184
|
[
"def _common(ret, name, service_name, kwargs):\n '''\n Returns: tuple whose first element is a bool indicating success or failure\n and the second element is either a ret dict for salt or an object\n '''\n if 'interface' not in kwargs and 'public_url' not in kwargs:\n kwargs['interface'] = name\n service = __salt__['keystoneng.service_get'](name_or_id=service_name)\n\n if not service:\n ret['comment'] = 'Cannot find service'\n ret['result'] = False\n return (False, ret)\n\n filters = kwargs.copy()\n filters.pop('enabled', None)\n filters.pop('url', None)\n filters['service_id'] = service.id\n kwargs['service_name_or_id'] = service.id\n endpoints = __salt__['keystoneng.endpoint_search'](filters=filters)\n\n if len(endpoints) > 1:\n ret['comment'] = \"Multiple endpoints match criteria\"\n ret['result'] = False\n return ret\n endpoint = endpoints[0] if endpoints else None\n return (True, endpoint)\n"
] |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Keystone Endpoints
==========================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions
Example States
.. code-block:: yaml
create endpoint:
keystone_endpoint.present:
- name: public
- url: https://example.org:9292
- region: RegionOne
- service_name: glance
destroy endpoint:
keystone_endpoint.absent:
- name: public
- url: https://example.org:9292
- region: RegionOne
- service_name: glance
create multiple endpoints:
keystone_endpoint.absent:
- names:
- public
- admin
- internal
- url: https://example.org:9292
- region: RegionOne
- service_name: glance
'''
from __future__ import absolute_import, unicode_literals, print_function
__virtualname__ = 'keystone_endpoint'
def __virtual__():
if 'keystoneng.endpoint_get' in __salt__:
return __virtualname__
return (False, 'The keystoneng execution module failed to load: shade python module is not available')
def _common(ret, name, service_name, kwargs):
'''
Returns: tuple whose first element is a bool indicating success or failure
and the second element is either a ret dict for salt or an object
'''
if 'interface' not in kwargs and 'public_url' not in kwargs:
kwargs['interface'] = name
service = __salt__['keystoneng.service_get'](name_or_id=service_name)
if not service:
ret['comment'] = 'Cannot find service'
ret['result'] = False
return (False, ret)
filters = kwargs.copy()
filters.pop('enabled', None)
filters.pop('url', None)
filters['service_id'] = service.id
kwargs['service_name_or_id'] = service.id
endpoints = __salt__['keystoneng.endpoint_search'](filters=filters)
if len(endpoints) > 1:
ret['comment'] = "Multiple endpoints match criteria"
ret['result'] = False
return ret
endpoint = endpoints[0] if endpoints else None
return (True, endpoint)
def present(name, service_name, auth=None, **kwargs):
'''
Ensure an endpoint exists and is up-to-date
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
enabled
Boolean to control if endpoint is enabled
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_clouds'](auth)
success, val = _, endpoint = _common(ret, name, service_name, kwargs)
if not success:
return val
if not endpoint:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Endpoint will be created.'
return ret
# NOTE(SamYaple): Endpoints are returned as a list which can contain
# several items depending on the options passed
endpoints = __salt__['keystoneng.endpoint_create'](**kwargs)
if len(endpoints) == 1:
ret['changes'] = endpoints[0]
else:
for i, endpoint in enumerate(endpoints):
ret['changes'][i] = endpoint
ret['comment'] = 'Created endpoint'
return ret
changes = __salt__['keystoneng.compare_changes'](endpoint, **kwargs)
if changes:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = changes
ret['comment'] = 'Endpoint will be updated.'
return ret
kwargs['endpoint_id'] = endpoint.id
__salt__['keystoneng.endpoint_update'](**kwargs)
ret['changes'].update(changes)
ret['comment'] = 'Updated endpoint'
return ret
|
saltstack/salt
|
salt/runners/bgp.py
|
_get_bgp_runner_opts
|
python
|
def _get_bgp_runner_opts():
'''
Return the bgp runner options.
'''
runner_opts = __opts__.get('runners', {}).get('bgp', {})
return {
'tgt': runner_opts.get('tgt', _DEFAULT_TARGET),
'tgt_type': runner_opts.get('tgt_type', _DEFAULT_EXPR_FORM),
'display': runner_opts.get('display', _DEFAULT_DISPLAY),
'return_fields': _DEFAULT_INCLUDED_FIELDS + runner_opts.get('return_fields', _DEFAULT_RETURN_FIELDS),
'outputter': runner_opts.get('outputter', _DEFAULT_OUTPUTTER),
}
|
Return the bgp runner options.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/bgp.py#L167-L178
| null |
# -*- coding: utf-8 -*-
'''
BGP Finder
==========
.. versionadded:: 2017.7.0
Runner to search BGP neighbors details.
Configuration
-------------
- Minion (proxy) config
The ``bgp.neighbors`` function must be appened in the list of ``mine_functions``:
.. code-block:: yaml
mine_functions:
bgp.neighbors: []
Which instructs Salt to cache the data returned by the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>`.
How often the mines are refreshed, can be specified using:
.. code-block:: yaml
mine_interval: <X minutes>
- Master config
By default the following options can be configured on the master.
They are not mandatory, but available in case the user has different requirements.
tgt: ``*``
From what minions will collect the mine data.
Default: ``*`` (collect mine data from all minions)
tgt_type: ``glob``
Minion matching expression form. Default: ``glob``.
return_fields
What fields to return in the output.
It can display all the fields from the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>`.
Some fields cannot be removed:
- ``as_number``: the AS number of the neighbor
- ``device``: the minion ID
- ``neighbor_address``: the neighbor remote IP address
By default, the following extra fields are returned (displayed):
- ``connection_stats``: connection stats, as described below
- ``import_policy``: the name of the import policy
- ``export_policy``: the name of the export policy
Special fields:
- ``vrf``: return the name of the VRF.
- ``connection_stats``: returning an output of the form ``<State>
<Active>/<Received>/<Accepted>/<Damped>``, e.g. ``Established
398/399/399/0`` similar to the usual output from network devices.
- ``interface_description``: matches the neighbor details with the
corresponding interface and returns its description. This will reuse
functionality from the :mod:`net runner
<salt.runners.net.interfaces>`, so the user needs to enable the mines
as specified in the documentation.
- ``interface_name``: matches the neighbor details with the
corresponding interface and returns the name. Similar to
``interface_description``, this will reuse functionality from the
:mod:`net runner <salt.runners.net.interfaces>`, so the user needs to
enable the mines as specified in the documentation.
display: ``True``
Display on the screen or return structured object? Default: ``True`` (return on the CLI).
outputter: ``table``
Specify the outputter name when displaying on the CLI. Default: :mod:`table <salt.output.table_out>`.
Configuration example:
.. code-block:: yaml
runners:
bgp:
tgt: 'edge*'
tgt_type: 'glob'
return_fields:
- up
- connection_state
- previous_connection_state
- suppress_4byte_as
- holdtime
- flap_count
outputter: yaml
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import third party libs
try:
from netaddr import IPNetwork
from netaddr import IPAddress
# pylint: disable=unused-import
from napalm_base import helpers as napalm_helpers
# pylint: enable=unused-import
HAS_NAPALM_BASE = True
except ImportError:
HAS_NAPALM_BASE = False
# Import salt lib
import salt.output
from salt.ext import six
from salt.ext.six.moves import map
# -----------------------------------------------------------------------------
# module properties
# -----------------------------------------------------------------------------
__virtualname__ = 'bgp'
# -----------------------------------------------------------------------------
# global variables
# -----------------------------------------------------------------------------
_DEFAULT_TARGET = '*'
_DEFAULT_EXPR_FORM = 'glob'
_DEFAULT_DISPLAY = True
_DEFAULT_OUTPUTTER = 'table'
_DEFAULT_INCLUDED_FIELDS = [
'device',
'as_number',
'neighbor_address'
]
_DEFAULT_RETURN_FIELDS = [
'connection_stats',
'import_policy',
'export_policy'
]
_DEFAULT_LABELS_MAPPING = {
'device': 'Device',
'as_number': 'AS Number',
'neighbor_address': 'Neighbor IP',
'connection_stats': 'State|#Active/Received/Accepted/Damped',
'import_policy': 'Policy IN',
'export_policy': 'Policy OUT',
'vrf': 'VRF'
}
# -----------------------------------------------------------------------------
# property functions
# -----------------------------------------------------------------------------
def __virtual__():
if HAS_NAPALM_BASE:
return __virtualname__
return (False, 'The napalm-base module could not be imported')
# -----------------------------------------------------------------------------
# helper functions -- will not be exported
# -----------------------------------------------------------------------------
def _get_mine(opts=None):
'''
Helper to return the mine data from the minions, as configured on the runner opts.
'''
if not opts:
# not a massive improvement, but better than recomputing the runner opts dict
opts = _get_bgp_runner_opts()
return __salt__['mine.get'](opts['tgt'],
'bgp.neighbors',
tgt_type=opts['tgt_type'])
def _compare_match(dict1, dict2):
'''
Compare two dictionaries and return a boolean value if their values match.
'''
for karg, warg in six.iteritems(dict1):
if karg in dict2 and dict2[karg] != warg:
return False
return True
def _display_runner(rows,
labels,
title,
display=_DEFAULT_DISPLAY,
outputter=_DEFAULT_OUTPUTTER):
'''
Display or return the rows.
'''
if display:
if outputter == 'table':
ret = salt.output.out_format({'rows': rows, 'labels': labels},
'table',
__opts__,
title=title,
rows_key='rows',
labels_key='labels')
else:
ret = salt.output.out_format(rows,
outputter,
__opts__)
print(ret)
else:
return rows
# -----------------------------------------------------------------------------
# callable functions
# -----------------------------------------------------------------------------
def neighbors(*asns, **kwargs):
'''
Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function.
Arguments:
asns
A list of AS numbers to search for.
The runner will return only the neighbors of these AS numbers.
device
Filter by device name (minion ID).
ip
Search BGP neighbor using the IP address.
In multi-VRF environments, the same IP address could be used by
more than one neighbors, in different routing tables.
network
Search neighbors within a certain IP network.
title
Custom title.
display: ``True``
Display on the screen or return structured object? Default: ``True`` (return on the CLI).
outputter: ``table``
Specify the outputter name when displaying on the CLI. Default: :mod:`table <salt.output.table_out>`.
In addition, any field from the output of the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>` can be used as a filter.
CLI Example:
.. code-block:: bash
salt-run bgp.neighbors 13335 15169
salt-run bgp.neighbors 13335 ip=172.17.19.1
salt-run bgp.neighbors multipath=True
salt-run bgp.neighbors up=False export_policy=my-export-policy multihop=False
salt-run bgp.neighbors network=192.168.0.0/16
Output example:
.. code-block:: text
BGP Neighbors for 13335, 15169
________________________________________________________________________________________________________________________________________________________________
| Device | AS Number | Neighbor Address | State|#Active/Received/Accepted/Damped | Policy IN | Policy OUT |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.11 | Established 0/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.12 | Established 397/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.flw01 | 13335 | 192.168.172.11 | Established 1/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.oua01 | 13335 | 172.17.109.17 | Established 0/0/0/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::1 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::2 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.tbg01 | 13335 | 192.168.172.17 | Established 0/1/1/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
'''
opts = _get_bgp_runner_opts()
title = kwargs.pop('title', None)
display = kwargs.pop('display', opts['display'])
outputter = kwargs.pop('outputter', opts['outputter'])
# cleaning up the kwargs
# __pub args not used in this runner (yet)
kwargs_copy = {}
kwargs_copy.update(kwargs)
for karg, _ in six.iteritems(kwargs_copy):
if karg.startswith('__pub'):
kwargs.pop(karg)
if not asns and not kwargs:
if display:
print('Please specify at least an AS Number or an output filter')
return []
device = kwargs.pop('device', None)
neighbor_ip = kwargs.pop('ip', None)
ipnet = kwargs.pop('network', None)
ipnet_obj = IPNetwork(ipnet) if ipnet else None
# any other key passed on the CLI can be used as a filter
rows = []
# building the labels
labels = {}
for field in opts['return_fields']:
if field in _DEFAULT_LABELS_MAPPING:
labels[field] = _DEFAULT_LABELS_MAPPING[field]
else:
# transform from 'previous_connection_state' to 'Previous Connection State'
labels[field] = ' '.join(map(lambda word: word.title(), field.split('_')))
display_fields = list(set(opts['return_fields']) - set(_DEFAULT_INCLUDED_FIELDS))
get_bgp_neighbors_all = _get_mine(opts=opts)
if not title:
title_parts = []
if asns:
title_parts.append('BGP Neighbors for {asns}'.format(
asns=', '.join([six.text_type(asn) for asn in asns])
))
if neighbor_ip:
title_parts.append('Selecting neighbors having the remote IP address: {ipaddr}'.format(ipaddr=neighbor_ip))
if ipnet:
title_parts.append('Selecting neighbors within the IP network: {ipnet}'.format(ipnet=ipnet))
if kwargs:
title_parts.append('Searching for BGP neighbors having the attributes: {attrmap}'.format(
attrmap=', '.join(map(lambda key: '{key}={value}'.format(key=key, value=kwargs[key]), kwargs))
))
title = '\n'.join(title_parts)
for minion, get_bgp_neighbors_minion in six.iteritems(get_bgp_neighbors_all): # pylint: disable=too-many-nested-blocks
if not get_bgp_neighbors_minion.get('result'):
continue # ignore empty or failed mines
if device and minion != device:
# when requested to display only the neighbors on a certain device
continue
get_bgp_neighbors_minion_out = get_bgp_neighbors_minion.get('out', {})
for vrf, vrf_bgp_neighbors in six.iteritems(get_bgp_neighbors_minion_out): # pylint: disable=unused-variable
for asn, get_bgp_neighbors_minion_asn in six.iteritems(vrf_bgp_neighbors):
if asns and asn not in asns:
# if filtering by AS number(s),
# will ignore if this AS number key not in that list
# and continue the search
continue
for neighbor in get_bgp_neighbors_minion_asn:
if kwargs and not _compare_match(kwargs, neighbor):
# requested filtering by neighbors stats
# but this one does not correspond
continue
if neighbor_ip and neighbor_ip != neighbor.get('remote_address'):
# requested filtering by neighbors IP addr
continue
if ipnet_obj and neighbor.get('remote_address'):
neighbor_ip_obj = IPAddress(neighbor.get('remote_address'))
if neighbor_ip_obj not in ipnet_obj:
# Neighbor not in this network
continue
row = {
'device': minion,
'neighbor_address': neighbor.get('remote_address'),
'as_number': asn
}
if 'vrf' in display_fields:
row['vrf'] = vrf
if 'connection_stats' in display_fields:
connection_stats = '{state} {active}/{received}/{accepted}/{damped}'.format(
state=neighbor.get('connection_state', -1),
active=neighbor.get('active_prefix_count', -1),
received=neighbor.get('received_prefix_count', -1),
accepted=neighbor.get('accepted_prefix_count', -1),
damped=neighbor.get('suppressed_prefix_count', -1),
)
row['connection_stats'] = connection_stats
if 'interface_description' in display_fields or 'interface_name' in display_fields:
net_find = __salt__['net.interfaces'](device=minion,
ipnet=neighbor.get('remote_address'),
display=False)
if net_find:
if 'interface_description' in display_fields:
row['interface_description'] = net_find[0]['interface_description']
if 'interface_name' in display_fields:
row['interface_name'] = net_find[0]['interface']
else:
# if unable to find anything, leave blank
if 'interface_description' in display_fields:
row['interface_description'] = ''
if 'interface_name' in display_fields:
row['interface_name'] = ''
for field in display_fields:
if field in neighbor:
row[field] = neighbor[field]
rows.append(row)
return _display_runner(rows, labels, title, display=display, outputter=outputter)
|
saltstack/salt
|
salt/runners/bgp.py
|
_compare_match
|
python
|
def _compare_match(dict1, dict2):
'''
Compare two dictionaries and return a boolean value if their values match.
'''
for karg, warg in six.iteritems(dict1):
if karg in dict2 and dict2[karg] != warg:
return False
return True
|
Compare two dictionaries and return a boolean value if their values match.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/bgp.py#L193-L200
| null |
# -*- coding: utf-8 -*-
'''
BGP Finder
==========
.. versionadded:: 2017.7.0
Runner to search BGP neighbors details.
Configuration
-------------
- Minion (proxy) config
The ``bgp.neighbors`` function must be appened in the list of ``mine_functions``:
.. code-block:: yaml
mine_functions:
bgp.neighbors: []
Which instructs Salt to cache the data returned by the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>`.
How often the mines are refreshed, can be specified using:
.. code-block:: yaml
mine_interval: <X minutes>
- Master config
By default the following options can be configured on the master.
They are not mandatory, but available in case the user has different requirements.
tgt: ``*``
From what minions will collect the mine data.
Default: ``*`` (collect mine data from all minions)
tgt_type: ``glob``
Minion matching expression form. Default: ``glob``.
return_fields
What fields to return in the output.
It can display all the fields from the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>`.
Some fields cannot be removed:
- ``as_number``: the AS number of the neighbor
- ``device``: the minion ID
- ``neighbor_address``: the neighbor remote IP address
By default, the following extra fields are returned (displayed):
- ``connection_stats``: connection stats, as described below
- ``import_policy``: the name of the import policy
- ``export_policy``: the name of the export policy
Special fields:
- ``vrf``: return the name of the VRF.
- ``connection_stats``: returning an output of the form ``<State>
<Active>/<Received>/<Accepted>/<Damped>``, e.g. ``Established
398/399/399/0`` similar to the usual output from network devices.
- ``interface_description``: matches the neighbor details with the
corresponding interface and returns its description. This will reuse
functionality from the :mod:`net runner
<salt.runners.net.interfaces>`, so the user needs to enable the mines
as specified in the documentation.
- ``interface_name``: matches the neighbor details with the
corresponding interface and returns the name. Similar to
``interface_description``, this will reuse functionality from the
:mod:`net runner <salt.runners.net.interfaces>`, so the user needs to
enable the mines as specified in the documentation.
display: ``True``
Display on the screen or return structured object? Default: ``True`` (return on the CLI).
outputter: ``table``
Specify the outputter name when displaying on the CLI. Default: :mod:`table <salt.output.table_out>`.
Configuration example:
.. code-block:: yaml
runners:
bgp:
tgt: 'edge*'
tgt_type: 'glob'
return_fields:
- up
- connection_state
- previous_connection_state
- suppress_4byte_as
- holdtime
- flap_count
outputter: yaml
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import third party libs
try:
from netaddr import IPNetwork
from netaddr import IPAddress
# pylint: disable=unused-import
from napalm_base import helpers as napalm_helpers
# pylint: enable=unused-import
HAS_NAPALM_BASE = True
except ImportError:
HAS_NAPALM_BASE = False
# Import salt lib
import salt.output
from salt.ext import six
from salt.ext.six.moves import map
# -----------------------------------------------------------------------------
# module properties
# -----------------------------------------------------------------------------
__virtualname__ = 'bgp'
# -----------------------------------------------------------------------------
# global variables
# -----------------------------------------------------------------------------
_DEFAULT_TARGET = '*'
_DEFAULT_EXPR_FORM = 'glob'
_DEFAULT_DISPLAY = True
_DEFAULT_OUTPUTTER = 'table'
_DEFAULT_INCLUDED_FIELDS = [
'device',
'as_number',
'neighbor_address'
]
_DEFAULT_RETURN_FIELDS = [
'connection_stats',
'import_policy',
'export_policy'
]
_DEFAULT_LABELS_MAPPING = {
'device': 'Device',
'as_number': 'AS Number',
'neighbor_address': 'Neighbor IP',
'connection_stats': 'State|#Active/Received/Accepted/Damped',
'import_policy': 'Policy IN',
'export_policy': 'Policy OUT',
'vrf': 'VRF'
}
# -----------------------------------------------------------------------------
# property functions
# -----------------------------------------------------------------------------
def __virtual__():
if HAS_NAPALM_BASE:
return __virtualname__
return (False, 'The napalm-base module could not be imported')
# -----------------------------------------------------------------------------
# helper functions -- will not be exported
# -----------------------------------------------------------------------------
def _get_bgp_runner_opts():
'''
Return the bgp runner options.
'''
runner_opts = __opts__.get('runners', {}).get('bgp', {})
return {
'tgt': runner_opts.get('tgt', _DEFAULT_TARGET),
'tgt_type': runner_opts.get('tgt_type', _DEFAULT_EXPR_FORM),
'display': runner_opts.get('display', _DEFAULT_DISPLAY),
'return_fields': _DEFAULT_INCLUDED_FIELDS + runner_opts.get('return_fields', _DEFAULT_RETURN_FIELDS),
'outputter': runner_opts.get('outputter', _DEFAULT_OUTPUTTER),
}
def _get_mine(opts=None):
'''
Helper to return the mine data from the minions, as configured on the runner opts.
'''
if not opts:
# not a massive improvement, but better than recomputing the runner opts dict
opts = _get_bgp_runner_opts()
return __salt__['mine.get'](opts['tgt'],
'bgp.neighbors',
tgt_type=opts['tgt_type'])
def _display_runner(rows,
labels,
title,
display=_DEFAULT_DISPLAY,
outputter=_DEFAULT_OUTPUTTER):
'''
Display or return the rows.
'''
if display:
if outputter == 'table':
ret = salt.output.out_format({'rows': rows, 'labels': labels},
'table',
__opts__,
title=title,
rows_key='rows',
labels_key='labels')
else:
ret = salt.output.out_format(rows,
outputter,
__opts__)
print(ret)
else:
return rows
# -----------------------------------------------------------------------------
# callable functions
# -----------------------------------------------------------------------------
def neighbors(*asns, **kwargs):
'''
Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function.
Arguments:
asns
A list of AS numbers to search for.
The runner will return only the neighbors of these AS numbers.
device
Filter by device name (minion ID).
ip
Search BGP neighbor using the IP address.
In multi-VRF environments, the same IP address could be used by
more than one neighbors, in different routing tables.
network
Search neighbors within a certain IP network.
title
Custom title.
display: ``True``
Display on the screen or return structured object? Default: ``True`` (return on the CLI).
outputter: ``table``
Specify the outputter name when displaying on the CLI. Default: :mod:`table <salt.output.table_out>`.
In addition, any field from the output of the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>` can be used as a filter.
CLI Example:
.. code-block:: bash
salt-run bgp.neighbors 13335 15169
salt-run bgp.neighbors 13335 ip=172.17.19.1
salt-run bgp.neighbors multipath=True
salt-run bgp.neighbors up=False export_policy=my-export-policy multihop=False
salt-run bgp.neighbors network=192.168.0.0/16
Output example:
.. code-block:: text
BGP Neighbors for 13335, 15169
________________________________________________________________________________________________________________________________________________________________
| Device | AS Number | Neighbor Address | State|#Active/Received/Accepted/Damped | Policy IN | Policy OUT |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.11 | Established 0/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.12 | Established 397/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.flw01 | 13335 | 192.168.172.11 | Established 1/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.oua01 | 13335 | 172.17.109.17 | Established 0/0/0/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::1 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::2 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.tbg01 | 13335 | 192.168.172.17 | Established 0/1/1/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
'''
opts = _get_bgp_runner_opts()
title = kwargs.pop('title', None)
display = kwargs.pop('display', opts['display'])
outputter = kwargs.pop('outputter', opts['outputter'])
# cleaning up the kwargs
# __pub args not used in this runner (yet)
kwargs_copy = {}
kwargs_copy.update(kwargs)
for karg, _ in six.iteritems(kwargs_copy):
if karg.startswith('__pub'):
kwargs.pop(karg)
if not asns and not kwargs:
if display:
print('Please specify at least an AS Number or an output filter')
return []
device = kwargs.pop('device', None)
neighbor_ip = kwargs.pop('ip', None)
ipnet = kwargs.pop('network', None)
ipnet_obj = IPNetwork(ipnet) if ipnet else None
# any other key passed on the CLI can be used as a filter
rows = []
# building the labels
labels = {}
for field in opts['return_fields']:
if field in _DEFAULT_LABELS_MAPPING:
labels[field] = _DEFAULT_LABELS_MAPPING[field]
else:
# transform from 'previous_connection_state' to 'Previous Connection State'
labels[field] = ' '.join(map(lambda word: word.title(), field.split('_')))
display_fields = list(set(opts['return_fields']) - set(_DEFAULT_INCLUDED_FIELDS))
get_bgp_neighbors_all = _get_mine(opts=opts)
if not title:
title_parts = []
if asns:
title_parts.append('BGP Neighbors for {asns}'.format(
asns=', '.join([six.text_type(asn) for asn in asns])
))
if neighbor_ip:
title_parts.append('Selecting neighbors having the remote IP address: {ipaddr}'.format(ipaddr=neighbor_ip))
if ipnet:
title_parts.append('Selecting neighbors within the IP network: {ipnet}'.format(ipnet=ipnet))
if kwargs:
title_parts.append('Searching for BGP neighbors having the attributes: {attrmap}'.format(
attrmap=', '.join(map(lambda key: '{key}={value}'.format(key=key, value=kwargs[key]), kwargs))
))
title = '\n'.join(title_parts)
for minion, get_bgp_neighbors_minion in six.iteritems(get_bgp_neighbors_all): # pylint: disable=too-many-nested-blocks
if not get_bgp_neighbors_minion.get('result'):
continue # ignore empty or failed mines
if device and minion != device:
# when requested to display only the neighbors on a certain device
continue
get_bgp_neighbors_minion_out = get_bgp_neighbors_minion.get('out', {})
for vrf, vrf_bgp_neighbors in six.iteritems(get_bgp_neighbors_minion_out): # pylint: disable=unused-variable
for asn, get_bgp_neighbors_minion_asn in six.iteritems(vrf_bgp_neighbors):
if asns and asn not in asns:
# if filtering by AS number(s),
# will ignore if this AS number key not in that list
# and continue the search
continue
for neighbor in get_bgp_neighbors_minion_asn:
if kwargs and not _compare_match(kwargs, neighbor):
# requested filtering by neighbors stats
# but this one does not correspond
continue
if neighbor_ip and neighbor_ip != neighbor.get('remote_address'):
# requested filtering by neighbors IP addr
continue
if ipnet_obj and neighbor.get('remote_address'):
neighbor_ip_obj = IPAddress(neighbor.get('remote_address'))
if neighbor_ip_obj not in ipnet_obj:
# Neighbor not in this network
continue
row = {
'device': minion,
'neighbor_address': neighbor.get('remote_address'),
'as_number': asn
}
if 'vrf' in display_fields:
row['vrf'] = vrf
if 'connection_stats' in display_fields:
connection_stats = '{state} {active}/{received}/{accepted}/{damped}'.format(
state=neighbor.get('connection_state', -1),
active=neighbor.get('active_prefix_count', -1),
received=neighbor.get('received_prefix_count', -1),
accepted=neighbor.get('accepted_prefix_count', -1),
damped=neighbor.get('suppressed_prefix_count', -1),
)
row['connection_stats'] = connection_stats
if 'interface_description' in display_fields or 'interface_name' in display_fields:
net_find = __salt__['net.interfaces'](device=minion,
ipnet=neighbor.get('remote_address'),
display=False)
if net_find:
if 'interface_description' in display_fields:
row['interface_description'] = net_find[0]['interface_description']
if 'interface_name' in display_fields:
row['interface_name'] = net_find[0]['interface']
else:
# if unable to find anything, leave blank
if 'interface_description' in display_fields:
row['interface_description'] = ''
if 'interface_name' in display_fields:
row['interface_name'] = ''
for field in display_fields:
if field in neighbor:
row[field] = neighbor[field]
rows.append(row)
return _display_runner(rows, labels, title, display=display, outputter=outputter)
|
saltstack/salt
|
salt/runners/bgp.py
|
_display_runner
|
python
|
def _display_runner(rows,
labels,
title,
display=_DEFAULT_DISPLAY,
outputter=_DEFAULT_OUTPUTTER):
'''
Display or return the rows.
'''
if display:
if outputter == 'table':
ret = salt.output.out_format({'rows': rows, 'labels': labels},
'table',
__opts__,
title=title,
rows_key='rows',
labels_key='labels')
else:
ret = salt.output.out_format(rows,
outputter,
__opts__)
print(ret)
else:
return rows
|
Display or return the rows.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/bgp.py#L203-L225
| null |
# -*- coding: utf-8 -*-
'''
BGP Finder
==========
.. versionadded:: 2017.7.0
Runner to search BGP neighbors details.
Configuration
-------------
- Minion (proxy) config
The ``bgp.neighbors`` function must be appened in the list of ``mine_functions``:
.. code-block:: yaml
mine_functions:
bgp.neighbors: []
Which instructs Salt to cache the data returned by the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>`.
How often the mines are refreshed, can be specified using:
.. code-block:: yaml
mine_interval: <X minutes>
- Master config
By default the following options can be configured on the master.
They are not mandatory, but available in case the user has different requirements.
tgt: ``*``
From what minions will collect the mine data.
Default: ``*`` (collect mine data from all minions)
tgt_type: ``glob``
Minion matching expression form. Default: ``glob``.
return_fields
What fields to return in the output.
It can display all the fields from the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>`.
Some fields cannot be removed:
- ``as_number``: the AS number of the neighbor
- ``device``: the minion ID
- ``neighbor_address``: the neighbor remote IP address
By default, the following extra fields are returned (displayed):
- ``connection_stats``: connection stats, as described below
- ``import_policy``: the name of the import policy
- ``export_policy``: the name of the export policy
Special fields:
- ``vrf``: return the name of the VRF.
- ``connection_stats``: returning an output of the form ``<State>
<Active>/<Received>/<Accepted>/<Damped>``, e.g. ``Established
398/399/399/0`` similar to the usual output from network devices.
- ``interface_description``: matches the neighbor details with the
corresponding interface and returns its description. This will reuse
functionality from the :mod:`net runner
<salt.runners.net.interfaces>`, so the user needs to enable the mines
as specified in the documentation.
- ``interface_name``: matches the neighbor details with the
corresponding interface and returns the name. Similar to
``interface_description``, this will reuse functionality from the
:mod:`net runner <salt.runners.net.interfaces>`, so the user needs to
enable the mines as specified in the documentation.
display: ``True``
Display on the screen or return structured object? Default: ``True`` (return on the CLI).
outputter: ``table``
Specify the outputter name when displaying on the CLI. Default: :mod:`table <salt.output.table_out>`.
Configuration example:
.. code-block:: yaml
runners:
bgp:
tgt: 'edge*'
tgt_type: 'glob'
return_fields:
- up
- connection_state
- previous_connection_state
- suppress_4byte_as
- holdtime
- flap_count
outputter: yaml
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import third party libs
try:
from netaddr import IPNetwork
from netaddr import IPAddress
# pylint: disable=unused-import
from napalm_base import helpers as napalm_helpers
# pylint: enable=unused-import
HAS_NAPALM_BASE = True
except ImportError:
HAS_NAPALM_BASE = False
# Import salt lib
import salt.output
from salt.ext import six
from salt.ext.six.moves import map
# -----------------------------------------------------------------------------
# module properties
# -----------------------------------------------------------------------------
__virtualname__ = 'bgp'
# -----------------------------------------------------------------------------
# global variables
# -----------------------------------------------------------------------------
_DEFAULT_TARGET = '*'
_DEFAULT_EXPR_FORM = 'glob'
_DEFAULT_DISPLAY = True
_DEFAULT_OUTPUTTER = 'table'
_DEFAULT_INCLUDED_FIELDS = [
'device',
'as_number',
'neighbor_address'
]
_DEFAULT_RETURN_FIELDS = [
'connection_stats',
'import_policy',
'export_policy'
]
_DEFAULT_LABELS_MAPPING = {
'device': 'Device',
'as_number': 'AS Number',
'neighbor_address': 'Neighbor IP',
'connection_stats': 'State|#Active/Received/Accepted/Damped',
'import_policy': 'Policy IN',
'export_policy': 'Policy OUT',
'vrf': 'VRF'
}
# -----------------------------------------------------------------------------
# property functions
# -----------------------------------------------------------------------------
def __virtual__():
if HAS_NAPALM_BASE:
return __virtualname__
return (False, 'The napalm-base module could not be imported')
# -----------------------------------------------------------------------------
# helper functions -- will not be exported
# -----------------------------------------------------------------------------
def _get_bgp_runner_opts():
'''
Return the bgp runner options.
'''
runner_opts = __opts__.get('runners', {}).get('bgp', {})
return {
'tgt': runner_opts.get('tgt', _DEFAULT_TARGET),
'tgt_type': runner_opts.get('tgt_type', _DEFAULT_EXPR_FORM),
'display': runner_opts.get('display', _DEFAULT_DISPLAY),
'return_fields': _DEFAULT_INCLUDED_FIELDS + runner_opts.get('return_fields', _DEFAULT_RETURN_FIELDS),
'outputter': runner_opts.get('outputter', _DEFAULT_OUTPUTTER),
}
def _get_mine(opts=None):
'''
Helper to return the mine data from the minions, as configured on the runner opts.
'''
if not opts:
# not a massive improvement, but better than recomputing the runner opts dict
opts = _get_bgp_runner_opts()
return __salt__['mine.get'](opts['tgt'],
'bgp.neighbors',
tgt_type=opts['tgt_type'])
def _compare_match(dict1, dict2):
'''
Compare two dictionaries and return a boolean value if their values match.
'''
for karg, warg in six.iteritems(dict1):
if karg in dict2 and dict2[karg] != warg:
return False
return True
# -----------------------------------------------------------------------------
# callable functions
# -----------------------------------------------------------------------------
def neighbors(*asns, **kwargs):
'''
Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function.
Arguments:
asns
A list of AS numbers to search for.
The runner will return only the neighbors of these AS numbers.
device
Filter by device name (minion ID).
ip
Search BGP neighbor using the IP address.
In multi-VRF environments, the same IP address could be used by
more than one neighbors, in different routing tables.
network
Search neighbors within a certain IP network.
title
Custom title.
display: ``True``
Display on the screen or return structured object? Default: ``True`` (return on the CLI).
outputter: ``table``
Specify the outputter name when displaying on the CLI. Default: :mod:`table <salt.output.table_out>`.
In addition, any field from the output of the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>` can be used as a filter.
CLI Example:
.. code-block:: bash
salt-run bgp.neighbors 13335 15169
salt-run bgp.neighbors 13335 ip=172.17.19.1
salt-run bgp.neighbors multipath=True
salt-run bgp.neighbors up=False export_policy=my-export-policy multihop=False
salt-run bgp.neighbors network=192.168.0.0/16
Output example:
.. code-block:: text
BGP Neighbors for 13335, 15169
________________________________________________________________________________________________________________________________________________________________
| Device | AS Number | Neighbor Address | State|#Active/Received/Accepted/Damped | Policy IN | Policy OUT |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.11 | Established 0/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.12 | Established 397/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.flw01 | 13335 | 192.168.172.11 | Established 1/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.oua01 | 13335 | 172.17.109.17 | Established 0/0/0/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::1 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::2 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.tbg01 | 13335 | 192.168.172.17 | Established 0/1/1/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
'''
opts = _get_bgp_runner_opts()
title = kwargs.pop('title', None)
display = kwargs.pop('display', opts['display'])
outputter = kwargs.pop('outputter', opts['outputter'])
# cleaning up the kwargs
# __pub args not used in this runner (yet)
kwargs_copy = {}
kwargs_copy.update(kwargs)
for karg, _ in six.iteritems(kwargs_copy):
if karg.startswith('__pub'):
kwargs.pop(karg)
if not asns and not kwargs:
if display:
print('Please specify at least an AS Number or an output filter')
return []
device = kwargs.pop('device', None)
neighbor_ip = kwargs.pop('ip', None)
ipnet = kwargs.pop('network', None)
ipnet_obj = IPNetwork(ipnet) if ipnet else None
# any other key passed on the CLI can be used as a filter
rows = []
# building the labels
labels = {}
for field in opts['return_fields']:
if field in _DEFAULT_LABELS_MAPPING:
labels[field] = _DEFAULT_LABELS_MAPPING[field]
else:
# transform from 'previous_connection_state' to 'Previous Connection State'
labels[field] = ' '.join(map(lambda word: word.title(), field.split('_')))
display_fields = list(set(opts['return_fields']) - set(_DEFAULT_INCLUDED_FIELDS))
get_bgp_neighbors_all = _get_mine(opts=opts)
if not title:
title_parts = []
if asns:
title_parts.append('BGP Neighbors for {asns}'.format(
asns=', '.join([six.text_type(asn) for asn in asns])
))
if neighbor_ip:
title_parts.append('Selecting neighbors having the remote IP address: {ipaddr}'.format(ipaddr=neighbor_ip))
if ipnet:
title_parts.append('Selecting neighbors within the IP network: {ipnet}'.format(ipnet=ipnet))
if kwargs:
title_parts.append('Searching for BGP neighbors having the attributes: {attrmap}'.format(
attrmap=', '.join(map(lambda key: '{key}={value}'.format(key=key, value=kwargs[key]), kwargs))
))
title = '\n'.join(title_parts)
for minion, get_bgp_neighbors_minion in six.iteritems(get_bgp_neighbors_all): # pylint: disable=too-many-nested-blocks
if not get_bgp_neighbors_minion.get('result'):
continue # ignore empty or failed mines
if device and minion != device:
# when requested to display only the neighbors on a certain device
continue
get_bgp_neighbors_minion_out = get_bgp_neighbors_minion.get('out', {})
for vrf, vrf_bgp_neighbors in six.iteritems(get_bgp_neighbors_minion_out): # pylint: disable=unused-variable
for asn, get_bgp_neighbors_minion_asn in six.iteritems(vrf_bgp_neighbors):
if asns and asn not in asns:
# if filtering by AS number(s),
# will ignore if this AS number key not in that list
# and continue the search
continue
for neighbor in get_bgp_neighbors_minion_asn:
if kwargs and not _compare_match(kwargs, neighbor):
# requested filtering by neighbors stats
# but this one does not correspond
continue
if neighbor_ip and neighbor_ip != neighbor.get('remote_address'):
# requested filtering by neighbors IP addr
continue
if ipnet_obj and neighbor.get('remote_address'):
neighbor_ip_obj = IPAddress(neighbor.get('remote_address'))
if neighbor_ip_obj not in ipnet_obj:
# Neighbor not in this network
continue
row = {
'device': minion,
'neighbor_address': neighbor.get('remote_address'),
'as_number': asn
}
if 'vrf' in display_fields:
row['vrf'] = vrf
if 'connection_stats' in display_fields:
connection_stats = '{state} {active}/{received}/{accepted}/{damped}'.format(
state=neighbor.get('connection_state', -1),
active=neighbor.get('active_prefix_count', -1),
received=neighbor.get('received_prefix_count', -1),
accepted=neighbor.get('accepted_prefix_count', -1),
damped=neighbor.get('suppressed_prefix_count', -1),
)
row['connection_stats'] = connection_stats
if 'interface_description' in display_fields or 'interface_name' in display_fields:
net_find = __salt__['net.interfaces'](device=minion,
ipnet=neighbor.get('remote_address'),
display=False)
if net_find:
if 'interface_description' in display_fields:
row['interface_description'] = net_find[0]['interface_description']
if 'interface_name' in display_fields:
row['interface_name'] = net_find[0]['interface']
else:
# if unable to find anything, leave blank
if 'interface_description' in display_fields:
row['interface_description'] = ''
if 'interface_name' in display_fields:
row['interface_name'] = ''
for field in display_fields:
if field in neighbor:
row[field] = neighbor[field]
rows.append(row)
return _display_runner(rows, labels, title, display=display, outputter=outputter)
|
saltstack/salt
|
salt/runners/bgp.py
|
neighbors
|
python
|
def neighbors(*asns, **kwargs):
'''
Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function.
Arguments:
asns
A list of AS numbers to search for.
The runner will return only the neighbors of these AS numbers.
device
Filter by device name (minion ID).
ip
Search BGP neighbor using the IP address.
In multi-VRF environments, the same IP address could be used by
more than one neighbors, in different routing tables.
network
Search neighbors within a certain IP network.
title
Custom title.
display: ``True``
Display on the screen or return structured object? Default: ``True`` (return on the CLI).
outputter: ``table``
Specify the outputter name when displaying on the CLI. Default: :mod:`table <salt.output.table_out>`.
In addition, any field from the output of the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>` can be used as a filter.
CLI Example:
.. code-block:: bash
salt-run bgp.neighbors 13335 15169
salt-run bgp.neighbors 13335 ip=172.17.19.1
salt-run bgp.neighbors multipath=True
salt-run bgp.neighbors up=False export_policy=my-export-policy multihop=False
salt-run bgp.neighbors network=192.168.0.0/16
Output example:
.. code-block:: text
BGP Neighbors for 13335, 15169
________________________________________________________________________________________________________________________________________________________________
| Device | AS Number | Neighbor Address | State|#Active/Received/Accepted/Damped | Policy IN | Policy OUT |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.11 | Established 0/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.12 | Established 397/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.flw01 | 13335 | 192.168.172.11 | Established 1/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.oua01 | 13335 | 172.17.109.17 | Established 0/0/0/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::1 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::2 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.tbg01 | 13335 | 192.168.172.17 | Established 0/1/1/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
'''
opts = _get_bgp_runner_opts()
title = kwargs.pop('title', None)
display = kwargs.pop('display', opts['display'])
outputter = kwargs.pop('outputter', opts['outputter'])
# cleaning up the kwargs
# __pub args not used in this runner (yet)
kwargs_copy = {}
kwargs_copy.update(kwargs)
for karg, _ in six.iteritems(kwargs_copy):
if karg.startswith('__pub'):
kwargs.pop(karg)
if not asns and not kwargs:
if display:
print('Please specify at least an AS Number or an output filter')
return []
device = kwargs.pop('device', None)
neighbor_ip = kwargs.pop('ip', None)
ipnet = kwargs.pop('network', None)
ipnet_obj = IPNetwork(ipnet) if ipnet else None
# any other key passed on the CLI can be used as a filter
rows = []
# building the labels
labels = {}
for field in opts['return_fields']:
if field in _DEFAULT_LABELS_MAPPING:
labels[field] = _DEFAULT_LABELS_MAPPING[field]
else:
# transform from 'previous_connection_state' to 'Previous Connection State'
labels[field] = ' '.join(map(lambda word: word.title(), field.split('_')))
display_fields = list(set(opts['return_fields']) - set(_DEFAULT_INCLUDED_FIELDS))
get_bgp_neighbors_all = _get_mine(opts=opts)
if not title:
title_parts = []
if asns:
title_parts.append('BGP Neighbors for {asns}'.format(
asns=', '.join([six.text_type(asn) for asn in asns])
))
if neighbor_ip:
title_parts.append('Selecting neighbors having the remote IP address: {ipaddr}'.format(ipaddr=neighbor_ip))
if ipnet:
title_parts.append('Selecting neighbors within the IP network: {ipnet}'.format(ipnet=ipnet))
if kwargs:
title_parts.append('Searching for BGP neighbors having the attributes: {attrmap}'.format(
attrmap=', '.join(map(lambda key: '{key}={value}'.format(key=key, value=kwargs[key]), kwargs))
))
title = '\n'.join(title_parts)
for minion, get_bgp_neighbors_minion in six.iteritems(get_bgp_neighbors_all): # pylint: disable=too-many-nested-blocks
if not get_bgp_neighbors_minion.get('result'):
continue # ignore empty or failed mines
if device and minion != device:
# when requested to display only the neighbors on a certain device
continue
get_bgp_neighbors_minion_out = get_bgp_neighbors_minion.get('out', {})
for vrf, vrf_bgp_neighbors in six.iteritems(get_bgp_neighbors_minion_out): # pylint: disable=unused-variable
for asn, get_bgp_neighbors_minion_asn in six.iteritems(vrf_bgp_neighbors):
if asns and asn not in asns:
# if filtering by AS number(s),
# will ignore if this AS number key not in that list
# and continue the search
continue
for neighbor in get_bgp_neighbors_minion_asn:
if kwargs and not _compare_match(kwargs, neighbor):
# requested filtering by neighbors stats
# but this one does not correspond
continue
if neighbor_ip and neighbor_ip != neighbor.get('remote_address'):
# requested filtering by neighbors IP addr
continue
if ipnet_obj and neighbor.get('remote_address'):
neighbor_ip_obj = IPAddress(neighbor.get('remote_address'))
if neighbor_ip_obj not in ipnet_obj:
# Neighbor not in this network
continue
row = {
'device': minion,
'neighbor_address': neighbor.get('remote_address'),
'as_number': asn
}
if 'vrf' in display_fields:
row['vrf'] = vrf
if 'connection_stats' in display_fields:
connection_stats = '{state} {active}/{received}/{accepted}/{damped}'.format(
state=neighbor.get('connection_state', -1),
active=neighbor.get('active_prefix_count', -1),
received=neighbor.get('received_prefix_count', -1),
accepted=neighbor.get('accepted_prefix_count', -1),
damped=neighbor.get('suppressed_prefix_count', -1),
)
row['connection_stats'] = connection_stats
if 'interface_description' in display_fields or 'interface_name' in display_fields:
net_find = __salt__['net.interfaces'](device=minion,
ipnet=neighbor.get('remote_address'),
display=False)
if net_find:
if 'interface_description' in display_fields:
row['interface_description'] = net_find[0]['interface_description']
if 'interface_name' in display_fields:
row['interface_name'] = net_find[0]['interface']
else:
# if unable to find anything, leave blank
if 'interface_description' in display_fields:
row['interface_description'] = ''
if 'interface_name' in display_fields:
row['interface_name'] = ''
for field in display_fields:
if field in neighbor:
row[field] = neighbor[field]
rows.append(row)
return _display_runner(rows, labels, title, display=display, outputter=outputter)
|
Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function.
Arguments:
asns
A list of AS numbers to search for.
The runner will return only the neighbors of these AS numbers.
device
Filter by device name (minion ID).
ip
Search BGP neighbor using the IP address.
In multi-VRF environments, the same IP address could be used by
more than one neighbors, in different routing tables.
network
Search neighbors within a certain IP network.
title
Custom title.
display: ``True``
Display on the screen or return structured object? Default: ``True`` (return on the CLI).
outputter: ``table``
Specify the outputter name when displaying on the CLI. Default: :mod:`table <salt.output.table_out>`.
In addition, any field from the output of the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>` can be used as a filter.
CLI Example:
.. code-block:: bash
salt-run bgp.neighbors 13335 15169
salt-run bgp.neighbors 13335 ip=172.17.19.1
salt-run bgp.neighbors multipath=True
salt-run bgp.neighbors up=False export_policy=my-export-policy multihop=False
salt-run bgp.neighbors network=192.168.0.0/16
Output example:
.. code-block:: text
BGP Neighbors for 13335, 15169
________________________________________________________________________________________________________________________________________________________________
| Device | AS Number | Neighbor Address | State|#Active/Received/Accepted/Damped | Policy IN | Policy OUT |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.11 | Established 0/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 13335 | 172.17.109.12 | Established 397/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.flw01 | 13335 | 192.168.172.11 | Established 1/398/398/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.oua01 | 13335 | 172.17.109.17 | Established 0/0/0/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::1 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.bjm01 | 15169 | 2001::2 | Established 102/102/102/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
| edge01.tbg01 | 13335 | 192.168.172.17 | Established 0/1/1/0 | import-policy | export-policy |
________________________________________________________________________________________________________________________________________________________________
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/bgp.py#L232-L409
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _get_bgp_runner_opts():\n '''\n Return the bgp runner options.\n '''\n runner_opts = __opts__.get('runners', {}).get('bgp', {})\n return {\n 'tgt': runner_opts.get('tgt', _DEFAULT_TARGET),\n 'tgt_type': runner_opts.get('tgt_type', _DEFAULT_EXPR_FORM),\n 'display': runner_opts.get('display', _DEFAULT_DISPLAY),\n 'return_fields': _DEFAULT_INCLUDED_FIELDS + runner_opts.get('return_fields', _DEFAULT_RETURN_FIELDS),\n 'outputter': runner_opts.get('outputter', _DEFAULT_OUTPUTTER),\n }\n",
"def _get_mine(opts=None):\n '''\n Helper to return the mine data from the minions, as configured on the runner opts.\n '''\n if not opts:\n # not a massive improvement, but better than recomputing the runner opts dict\n opts = _get_bgp_runner_opts()\n return __salt__['mine.get'](opts['tgt'],\n 'bgp.neighbors',\n tgt_type=opts['tgt_type'])\n",
"def _compare_match(dict1, dict2):\n '''\n Compare two dictionaries and return a boolean value if their values match.\n '''\n for karg, warg in six.iteritems(dict1):\n if karg in dict2 and dict2[karg] != warg:\n return False\n return True\n",
"def _display_runner(rows,\n labels,\n title,\n display=_DEFAULT_DISPLAY,\n outputter=_DEFAULT_OUTPUTTER):\n '''\n Display or return the rows.\n '''\n if display:\n if outputter == 'table':\n ret = salt.output.out_format({'rows': rows, 'labels': labels},\n 'table',\n __opts__,\n title=title,\n rows_key='rows',\n labels_key='labels')\n else:\n ret = salt.output.out_format(rows,\n outputter,\n __opts__)\n print(ret)\n else:\n return rows\n"
] |
# -*- coding: utf-8 -*-
'''
BGP Finder
==========
.. versionadded:: 2017.7.0
Runner to search BGP neighbors details.
Configuration
-------------
- Minion (proxy) config
The ``bgp.neighbors`` function must be appened in the list of ``mine_functions``:
.. code-block:: yaml
mine_functions:
bgp.neighbors: []
Which instructs Salt to cache the data returned by the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>`.
How often the mines are refreshed, can be specified using:
.. code-block:: yaml
mine_interval: <X minutes>
- Master config
By default the following options can be configured on the master.
They are not mandatory, but available in case the user has different requirements.
tgt: ``*``
From what minions will collect the mine data.
Default: ``*`` (collect mine data from all minions)
tgt_type: ``glob``
Minion matching expression form. Default: ``glob``.
return_fields
What fields to return in the output.
It can display all the fields from the ``neighbors`` function
from the :mod:`NAPALM BGP module <salt.modules.napalm_bgp.neighbors>`.
Some fields cannot be removed:
- ``as_number``: the AS number of the neighbor
- ``device``: the minion ID
- ``neighbor_address``: the neighbor remote IP address
By default, the following extra fields are returned (displayed):
- ``connection_stats``: connection stats, as described below
- ``import_policy``: the name of the import policy
- ``export_policy``: the name of the export policy
Special fields:
- ``vrf``: return the name of the VRF.
- ``connection_stats``: returning an output of the form ``<State>
<Active>/<Received>/<Accepted>/<Damped>``, e.g. ``Established
398/399/399/0`` similar to the usual output from network devices.
- ``interface_description``: matches the neighbor details with the
corresponding interface and returns its description. This will reuse
functionality from the :mod:`net runner
<salt.runners.net.interfaces>`, so the user needs to enable the mines
as specified in the documentation.
- ``interface_name``: matches the neighbor details with the
corresponding interface and returns the name. Similar to
``interface_description``, this will reuse functionality from the
:mod:`net runner <salt.runners.net.interfaces>`, so the user needs to
enable the mines as specified in the documentation.
display: ``True``
Display on the screen or return structured object? Default: ``True`` (return on the CLI).
outputter: ``table``
Specify the outputter name when displaying on the CLI. Default: :mod:`table <salt.output.table_out>`.
Configuration example:
.. code-block:: yaml
runners:
bgp:
tgt: 'edge*'
tgt_type: 'glob'
return_fields:
- up
- connection_state
- previous_connection_state
- suppress_4byte_as
- holdtime
- flap_count
outputter: yaml
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import third party libs
try:
from netaddr import IPNetwork
from netaddr import IPAddress
# pylint: disable=unused-import
from napalm_base import helpers as napalm_helpers
# pylint: enable=unused-import
HAS_NAPALM_BASE = True
except ImportError:
HAS_NAPALM_BASE = False
# Import salt lib
import salt.output
from salt.ext import six
from salt.ext.six.moves import map
# -----------------------------------------------------------------------------
# module properties
# -----------------------------------------------------------------------------
__virtualname__ = 'bgp'
# -----------------------------------------------------------------------------
# global variables
# -----------------------------------------------------------------------------
_DEFAULT_TARGET = '*'
_DEFAULT_EXPR_FORM = 'glob'
_DEFAULT_DISPLAY = True
_DEFAULT_OUTPUTTER = 'table'
_DEFAULT_INCLUDED_FIELDS = [
'device',
'as_number',
'neighbor_address'
]
_DEFAULT_RETURN_FIELDS = [
'connection_stats',
'import_policy',
'export_policy'
]
_DEFAULT_LABELS_MAPPING = {
'device': 'Device',
'as_number': 'AS Number',
'neighbor_address': 'Neighbor IP',
'connection_stats': 'State|#Active/Received/Accepted/Damped',
'import_policy': 'Policy IN',
'export_policy': 'Policy OUT',
'vrf': 'VRF'
}
# -----------------------------------------------------------------------------
# property functions
# -----------------------------------------------------------------------------
def __virtual__():
if HAS_NAPALM_BASE:
return __virtualname__
return (False, 'The napalm-base module could not be imported')
# -----------------------------------------------------------------------------
# helper functions -- will not be exported
# -----------------------------------------------------------------------------
def _get_bgp_runner_opts():
'''
Return the bgp runner options.
'''
runner_opts = __opts__.get('runners', {}).get('bgp', {})
return {
'tgt': runner_opts.get('tgt', _DEFAULT_TARGET),
'tgt_type': runner_opts.get('tgt_type', _DEFAULT_EXPR_FORM),
'display': runner_opts.get('display', _DEFAULT_DISPLAY),
'return_fields': _DEFAULT_INCLUDED_FIELDS + runner_opts.get('return_fields', _DEFAULT_RETURN_FIELDS),
'outputter': runner_opts.get('outputter', _DEFAULT_OUTPUTTER),
}
def _get_mine(opts=None):
'''
Helper to return the mine data from the minions, as configured on the runner opts.
'''
if not opts:
# not a massive improvement, but better than recomputing the runner opts dict
opts = _get_bgp_runner_opts()
return __salt__['mine.get'](opts['tgt'],
'bgp.neighbors',
tgt_type=opts['tgt_type'])
def _compare_match(dict1, dict2):
'''
Compare two dictionaries and return a boolean value if their values match.
'''
for karg, warg in six.iteritems(dict1):
if karg in dict2 and dict2[karg] != warg:
return False
return True
def _display_runner(rows,
labels,
title,
display=_DEFAULT_DISPLAY,
outputter=_DEFAULT_OUTPUTTER):
'''
Display or return the rows.
'''
if display:
if outputter == 'table':
ret = salt.output.out_format({'rows': rows, 'labels': labels},
'table',
__opts__,
title=title,
rows_key='rows',
labels_key='labels')
else:
ret = salt.output.out_format(rows,
outputter,
__opts__)
print(ret)
else:
return rows
# -----------------------------------------------------------------------------
# callable functions
# -----------------------------------------------------------------------------
|
saltstack/salt
|
salt/returners/mongo_future_return.py
|
_get_conn
|
python
|
def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
uri = _options.get('uri')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if uri and PYMONGO_VERSION > _LooseVersion('2.3'):
if uri and host:
raise salt.exceptions.SaltConfigurationError(
"Mongo returner expects either uri or host configuration. Both were provided")
pymongo.uri_parser.parse_uri(uri)
conn = pymongo.MongoClient(uri)
mdb = conn.get_database()
else:
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
if uri:
raise salt.exceptions.SaltConfigurationError(
"pymongo <= 2.3 does not support uri format")
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
mdb.events.create_index('tag')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
mdb.events.ensure_index('tag')
return conn, mdb
|
Return a mongodb connection object
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_future_return.py#L158-L207
|
[
"def _get_options(ret=None):\n '''\n Get the mongo options from salt.\n '''\n attrs = {'host': 'host',\n 'port': 'port',\n 'db': 'db',\n 'user': 'user',\n 'password': 'password',\n 'indexes': 'indexes',\n 'uri': 'uri'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n return _options\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a mongodb server
Required python modules: pymongo
This returner will send data from the minions to a MongoDB server. MongoDB
server can be configured by using host, port, db, user and password settings
or by connection string URI (for pymongo > 2.3). To configure the settings
for your MongoDB server, add the following lines to the minion config files:
.. code-block:: yaml
mongo.db: <database name>
mongo.host: <server ip address>
mongo.user: <MongoDB username>
mongo.password: <MongoDB user password>
mongo.port: 27017
Or single URI:
.. code-block:: yaml
mongo.uri: URI
where uri is in the format:
.. code-block:: text
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Example:
.. code-block:: text
mongodb://db1.example.net:27017/mydatabase
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000
More information on URI format can be found in
https://docs.mongodb.com/manual/reference/connection-string/
You can also ask for indexes creation on the most common used fields, which
should greatly improve performance. Indexes are not created by default.
.. code-block:: yaml
mongo.indexes: true
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.mongo.db: <database name>
alternative.mongo.host: <server ip address>
alternative.mongo.user: <MongoDB username>
alternative.mongo.password: <MongoDB user password>
alternative.mongo.port: 27017
Or single URI:
.. code-block:: yaml
alternative.mongo.uri: URI
This mongo returner is being developed to replace the default mongodb returner
in the future and should not be considered API stable yet.
To use the mongo returner, append '--return mongo' to the salt command.
.. code-block:: bash
salt '*' test.ping --return mongo
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.ext import six
from salt.utils.versions import LooseVersion as _LooseVersion
# Import third party libs
try:
import pymongo
PYMONGO_VERSION = _LooseVersion(pymongo.version)
HAS_PYMONGO = True
except ImportError:
HAS_PYMONGO = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'mongo'
def __virtual__():
if not HAS_PYMONGO:
return False, 'Could not import mongo returner; pymongo is not installed.'
return __virtualname__
def _remove_dots(src):
'''
Remove the dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
def _get_options(ret=None):
'''
Get the mongo options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password',
'indexes': 'indexes',
'uri': 'uri'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def returner(ret):
'''
Return data to a mongodb server
'''
conn, mdb = _get_conn(ret)
if isinstance(ret['return'], dict):
back = _remove_dots(ret['return'])
else:
back = ret['return']
if isinstance(ret, dict):
full_ret = _remove_dots(ret)
else:
full_ret = ret
log.debug(back)
sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret}
if 'out' in ret:
sdata['out'] = ret['out']
# save returns in the saltReturns collection in the json format:
# { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>,
# 'fun': <function>, 'full_ret': <unformatted return with dots removed>}
#
# again we run into the issue with deprecated code from previous versions
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure that the original data is not changed, raising issue with pymongo team
mdb.saltReturns.insert_one(sdata.copy())
else:
mdb.saltReturns.insert(sdata.copy())
def _safe_copy(dat):
''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encodings,
\\ --> %5c
$ --> %24
. --> %2e
Which means also escaping '%':
% -> %25
'''
if isinstance(dat, dict):
ret = {}
for k in dat:
r = k.replace('%', '%25').replace('\\', '%5c').replace('$', '%24').replace('.', '%2e')
if r != k:
log.debug('converting dict key from %s to %s for mongodb', k, r)
ret[r] = _safe_copy(dat[k])
return ret
if isinstance(dat, (list, tuple)):
return [_safe_copy(i) for i in dat]
return dat
def save_load(jid, load, minions=None):
'''
Save the load for a given job id
'''
conn, mdb = _get_conn(ret=None)
to_save = _safe_copy(load)
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure original data for load is unchanged
mdb.jobs.insert_one(to_save)
else:
mdb.jobs.insert(to_save)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load associated with a given job id
'''
conn, mdb = _get_conn(ret=None)
return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret
def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret
def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret
def get_jids():
'''
Return a list of job ids
'''
conn, mdb = _get_conn(ret=None)
map = "function() { emit(this.jid, this); }"
reduce = "function (key, values) { return values[0]; }"
result = mdb.jobs.inline_map_reduce(map, reduce)
ret = {}
for r in result:
jid = r['_id']
ret[jid] = salt.utils.jid.format_jid_instance(jid, r['value'])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def event_return(events):
'''
Return events to Mongodb server
'''
conn, mdb = _get_conn(ret=None)
if isinstance(events, list):
events = events[0]
if isinstance(events, dict):
log.debug(events)
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.events.insert_one(events.copy())
else:
mdb.events.insert(events.copy())
|
saltstack/salt
|
salt/returners/mongo_future_return.py
|
returner
|
python
|
def returner(ret):
'''
Return data to a mongodb server
'''
conn, mdb = _get_conn(ret)
if isinstance(ret['return'], dict):
back = _remove_dots(ret['return'])
else:
back = ret['return']
if isinstance(ret, dict):
full_ret = _remove_dots(ret)
else:
full_ret = ret
log.debug(back)
sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret}
if 'out' in ret:
sdata['out'] = ret['out']
# save returns in the saltReturns collection in the json format:
# { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>,
# 'fun': <function>, 'full_ret': <unformatted return with dots removed>}
#
# again we run into the issue with deprecated code from previous versions
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure that the original data is not changed, raising issue with pymongo team
mdb.saltReturns.insert_one(sdata.copy())
else:
mdb.saltReturns.insert(sdata.copy())
|
Return data to a mongodb server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_future_return.py#L210-L241
|
[
"def _get_conn(ret):\n '''\n Return a mongodb connection object\n '''\n _options = _get_options(ret)\n\n host = _options.get('host')\n port = _options.get('port')\n uri = _options.get('uri')\n db_ = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n indexes = _options.get('indexes', False)\n\n # at some point we should remove support for\n # pymongo versions < 2.3 until then there are\n # a bunch of these sections that need to be supported\n if uri and PYMONGO_VERSION > _LooseVersion('2.3'):\n if uri and host:\n raise salt.exceptions.SaltConfigurationError(\n \"Mongo returner expects either uri or host configuration. Both were provided\")\n pymongo.uri_parser.parse_uri(uri)\n conn = pymongo.MongoClient(uri)\n mdb = conn.get_database()\n else:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n conn = pymongo.MongoClient(host, port)\n else:\n if uri:\n raise salt.exceptions.SaltConfigurationError(\n \"pymongo <= 2.3 does not support uri format\")\n conn = pymongo.Connection(host, port)\n\n mdb = conn[db_]\n if user and password:\n mdb.authenticate(user, password)\n\n if indexes:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n mdb.saltReturns.create_index('minion')\n mdb.saltReturns.create_index('jid')\n mdb.jobs.create_index('jid')\n mdb.events.create_index('tag')\n else:\n mdb.saltReturns.ensure_index('minion')\n mdb.saltReturns.ensure_index('jid')\n mdb.jobs.ensure_index('jid')\n mdb.events.ensure_index('tag')\n\n return conn, mdb\n",
"def _remove_dots(src):\n '''\n Remove the dots from the given data structure\n '''\n output = {}\n for key, val in six.iteritems(src):\n if isinstance(val, dict):\n val = _remove_dots(val)\n output[key.replace('.', '-')] = val\n return output\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a mongodb server
Required python modules: pymongo
This returner will send data from the minions to a MongoDB server. MongoDB
server can be configured by using host, port, db, user and password settings
or by connection string URI (for pymongo > 2.3). To configure the settings
for your MongoDB server, add the following lines to the minion config files:
.. code-block:: yaml
mongo.db: <database name>
mongo.host: <server ip address>
mongo.user: <MongoDB username>
mongo.password: <MongoDB user password>
mongo.port: 27017
Or single URI:
.. code-block:: yaml
mongo.uri: URI
where uri is in the format:
.. code-block:: text
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Example:
.. code-block:: text
mongodb://db1.example.net:27017/mydatabase
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000
More information on URI format can be found in
https://docs.mongodb.com/manual/reference/connection-string/
You can also ask for indexes creation on the most common used fields, which
should greatly improve performance. Indexes are not created by default.
.. code-block:: yaml
mongo.indexes: true
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.mongo.db: <database name>
alternative.mongo.host: <server ip address>
alternative.mongo.user: <MongoDB username>
alternative.mongo.password: <MongoDB user password>
alternative.mongo.port: 27017
Or single URI:
.. code-block:: yaml
alternative.mongo.uri: URI
This mongo returner is being developed to replace the default mongodb returner
in the future and should not be considered API stable yet.
To use the mongo returner, append '--return mongo' to the salt command.
.. code-block:: bash
salt '*' test.ping --return mongo
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.ext import six
from salt.utils.versions import LooseVersion as _LooseVersion
# Import third party libs
try:
import pymongo
PYMONGO_VERSION = _LooseVersion(pymongo.version)
HAS_PYMONGO = True
except ImportError:
HAS_PYMONGO = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'mongo'
def __virtual__():
if not HAS_PYMONGO:
return False, 'Could not import mongo returner; pymongo is not installed.'
return __virtualname__
def _remove_dots(src):
'''
Remove the dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
def _get_options(ret=None):
'''
Get the mongo options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password',
'indexes': 'indexes',
'uri': 'uri'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
uri = _options.get('uri')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if uri and PYMONGO_VERSION > _LooseVersion('2.3'):
if uri and host:
raise salt.exceptions.SaltConfigurationError(
"Mongo returner expects either uri or host configuration. Both were provided")
pymongo.uri_parser.parse_uri(uri)
conn = pymongo.MongoClient(uri)
mdb = conn.get_database()
else:
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
if uri:
raise salt.exceptions.SaltConfigurationError(
"pymongo <= 2.3 does not support uri format")
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
mdb.events.create_index('tag')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
mdb.events.ensure_index('tag')
return conn, mdb
def _safe_copy(dat):
''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encodings,
\\ --> %5c
$ --> %24
. --> %2e
Which means also escaping '%':
% -> %25
'''
if isinstance(dat, dict):
ret = {}
for k in dat:
r = k.replace('%', '%25').replace('\\', '%5c').replace('$', '%24').replace('.', '%2e')
if r != k:
log.debug('converting dict key from %s to %s for mongodb', k, r)
ret[r] = _safe_copy(dat[k])
return ret
if isinstance(dat, (list, tuple)):
return [_safe_copy(i) for i in dat]
return dat
def save_load(jid, load, minions=None):
'''
Save the load for a given job id
'''
conn, mdb = _get_conn(ret=None)
to_save = _safe_copy(load)
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure original data for load is unchanged
mdb.jobs.insert_one(to_save)
else:
mdb.jobs.insert(to_save)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load associated with a given job id
'''
conn, mdb = _get_conn(ret=None)
return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret
def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret
def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret
def get_jids():
'''
Return a list of job ids
'''
conn, mdb = _get_conn(ret=None)
map = "function() { emit(this.jid, this); }"
reduce = "function (key, values) { return values[0]; }"
result = mdb.jobs.inline_map_reduce(map, reduce)
ret = {}
for r in result:
jid = r['_id']
ret[jid] = salt.utils.jid.format_jid_instance(jid, r['value'])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def event_return(events):
'''
Return events to Mongodb server
'''
conn, mdb = _get_conn(ret=None)
if isinstance(events, list):
events = events[0]
if isinstance(events, dict):
log.debug(events)
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.events.insert_one(events.copy())
else:
mdb.events.insert(events.copy())
|
saltstack/salt
|
salt/returners/mongo_future_return.py
|
_safe_copy
|
python
|
def _safe_copy(dat):
''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encodings,
\\ --> %5c
$ --> %24
. --> %2e
Which means also escaping '%':
% -> %25
'''
if isinstance(dat, dict):
ret = {}
for k in dat:
r = k.replace('%', '%25').replace('\\', '%5c').replace('$', '%24').replace('.', '%2e')
if r != k:
log.debug('converting dict key from %s to %s for mongodb', k, r)
ret[r] = _safe_copy(dat[k])
return ret
if isinstance(dat, (list, tuple)):
return [_safe_copy(i) for i in dat]
return dat
|
mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encodings,
\\ --> %5c
$ --> %24
. --> %2e
Which means also escaping '%':
% -> %25
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_future_return.py#L244-L277
|
[
"def _safe_copy(dat):\n ''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.\n Apparently the docs suggest using escaped unicode full-width\n encodings. *sigh*\n\n \\\\ --> \\\\\\\\\n $ --> \\\\\\\\u0024\n . --> \\\\\\\\u002e\n\n Personally, I prefer URL encodings,\n\n \\\\ --> %5c\n $ --> %24\n . --> %2e\n\n\n Which means also escaping '%':\n\n % -> %25\n '''\n\n if isinstance(dat, dict):\n ret = {}\n for k in dat:\n r = k.replace('%', '%25').replace('\\\\', '%5c').replace('$', '%24').replace('.', '%2e')\n if r != k:\n log.debug('converting dict key from %s to %s for mongodb', k, r)\n ret[r] = _safe_copy(dat[k])\n return ret\n\n if isinstance(dat, (list, tuple)):\n return [_safe_copy(i) for i in dat]\n\n return dat\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a mongodb server
Required python modules: pymongo
This returner will send data from the minions to a MongoDB server. MongoDB
server can be configured by using host, port, db, user and password settings
or by connection string URI (for pymongo > 2.3). To configure the settings
for your MongoDB server, add the following lines to the minion config files:
.. code-block:: yaml
mongo.db: <database name>
mongo.host: <server ip address>
mongo.user: <MongoDB username>
mongo.password: <MongoDB user password>
mongo.port: 27017
Or single URI:
.. code-block:: yaml
mongo.uri: URI
where uri is in the format:
.. code-block:: text
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Example:
.. code-block:: text
mongodb://db1.example.net:27017/mydatabase
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000
More information on URI format can be found in
https://docs.mongodb.com/manual/reference/connection-string/
You can also ask for indexes creation on the most common used fields, which
should greatly improve performance. Indexes are not created by default.
.. code-block:: yaml
mongo.indexes: true
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.mongo.db: <database name>
alternative.mongo.host: <server ip address>
alternative.mongo.user: <MongoDB username>
alternative.mongo.password: <MongoDB user password>
alternative.mongo.port: 27017
Or single URI:
.. code-block:: yaml
alternative.mongo.uri: URI
This mongo returner is being developed to replace the default mongodb returner
in the future and should not be considered API stable yet.
To use the mongo returner, append '--return mongo' to the salt command.
.. code-block:: bash
salt '*' test.ping --return mongo
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.ext import six
from salt.utils.versions import LooseVersion as _LooseVersion
# Import third party libs
try:
import pymongo
PYMONGO_VERSION = _LooseVersion(pymongo.version)
HAS_PYMONGO = True
except ImportError:
HAS_PYMONGO = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'mongo'
def __virtual__():
if not HAS_PYMONGO:
return False, 'Could not import mongo returner; pymongo is not installed.'
return __virtualname__
def _remove_dots(src):
'''
Remove the dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
def _get_options(ret=None):
'''
Get the mongo options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password',
'indexes': 'indexes',
'uri': 'uri'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
uri = _options.get('uri')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if uri and PYMONGO_VERSION > _LooseVersion('2.3'):
if uri and host:
raise salt.exceptions.SaltConfigurationError(
"Mongo returner expects either uri or host configuration. Both were provided")
pymongo.uri_parser.parse_uri(uri)
conn = pymongo.MongoClient(uri)
mdb = conn.get_database()
else:
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
if uri:
raise salt.exceptions.SaltConfigurationError(
"pymongo <= 2.3 does not support uri format")
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
mdb.events.create_index('tag')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
mdb.events.ensure_index('tag')
return conn, mdb
def returner(ret):
'''
Return data to a mongodb server
'''
conn, mdb = _get_conn(ret)
if isinstance(ret['return'], dict):
back = _remove_dots(ret['return'])
else:
back = ret['return']
if isinstance(ret, dict):
full_ret = _remove_dots(ret)
else:
full_ret = ret
log.debug(back)
sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret}
if 'out' in ret:
sdata['out'] = ret['out']
# save returns in the saltReturns collection in the json format:
# { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>,
# 'fun': <function>, 'full_ret': <unformatted return with dots removed>}
#
# again we run into the issue with deprecated code from previous versions
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure that the original data is not changed, raising issue with pymongo team
mdb.saltReturns.insert_one(sdata.copy())
else:
mdb.saltReturns.insert(sdata.copy())
def save_load(jid, load, minions=None):
'''
Save the load for a given job id
'''
conn, mdb = _get_conn(ret=None)
to_save = _safe_copy(load)
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure original data for load is unchanged
mdb.jobs.insert_one(to_save)
else:
mdb.jobs.insert(to_save)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load associated with a given job id
'''
conn, mdb = _get_conn(ret=None)
return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret
def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret
def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret
def get_jids():
'''
Return a list of job ids
'''
conn, mdb = _get_conn(ret=None)
map = "function() { emit(this.jid, this); }"
reduce = "function (key, values) { return values[0]; }"
result = mdb.jobs.inline_map_reduce(map, reduce)
ret = {}
for r in result:
jid = r['_id']
ret[jid] = salt.utils.jid.format_jid_instance(jid, r['value'])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def event_return(events):
'''
Return events to Mongodb server
'''
conn, mdb = _get_conn(ret=None)
if isinstance(events, list):
events = events[0]
if isinstance(events, dict):
log.debug(events)
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.events.insert_one(events.copy())
else:
mdb.events.insert(events.copy())
|
saltstack/salt
|
salt/returners/mongo_future_return.py
|
save_load
|
python
|
def save_load(jid, load, minions=None):
'''
Save the load for a given job id
'''
conn, mdb = _get_conn(ret=None)
to_save = _safe_copy(load)
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure original data for load is unchanged
mdb.jobs.insert_one(to_save)
else:
mdb.jobs.insert(to_save)
|
Save the load for a given job id
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_future_return.py#L280-L291
|
[
"def _get_conn(ret):\n '''\n Return a mongodb connection object\n '''\n _options = _get_options(ret)\n\n host = _options.get('host')\n port = _options.get('port')\n uri = _options.get('uri')\n db_ = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n indexes = _options.get('indexes', False)\n\n # at some point we should remove support for\n # pymongo versions < 2.3 until then there are\n # a bunch of these sections that need to be supported\n if uri and PYMONGO_VERSION > _LooseVersion('2.3'):\n if uri and host:\n raise salt.exceptions.SaltConfigurationError(\n \"Mongo returner expects either uri or host configuration. Both were provided\")\n pymongo.uri_parser.parse_uri(uri)\n conn = pymongo.MongoClient(uri)\n mdb = conn.get_database()\n else:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n conn = pymongo.MongoClient(host, port)\n else:\n if uri:\n raise salt.exceptions.SaltConfigurationError(\n \"pymongo <= 2.3 does not support uri format\")\n conn = pymongo.Connection(host, port)\n\n mdb = conn[db_]\n if user and password:\n mdb.authenticate(user, password)\n\n if indexes:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n mdb.saltReturns.create_index('minion')\n mdb.saltReturns.create_index('jid')\n mdb.jobs.create_index('jid')\n mdb.events.create_index('tag')\n else:\n mdb.saltReturns.ensure_index('minion')\n mdb.saltReturns.ensure_index('jid')\n mdb.jobs.ensure_index('jid')\n mdb.events.ensure_index('tag')\n\n return conn, mdb\n",
"def _safe_copy(dat):\n ''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.\n Apparently the docs suggest using escaped unicode full-width\n encodings. *sigh*\n\n \\\\ --> \\\\\\\\\n $ --> \\\\\\\\u0024\n . --> \\\\\\\\u002e\n\n Personally, I prefer URL encodings,\n\n \\\\ --> %5c\n $ --> %24\n . --> %2e\n\n\n Which means also escaping '%':\n\n % -> %25\n '''\n\n if isinstance(dat, dict):\n ret = {}\n for k in dat:\n r = k.replace('%', '%25').replace('\\\\', '%5c').replace('$', '%24').replace('.', '%2e')\n if r != k:\n log.debug('converting dict key from %s to %s for mongodb', k, r)\n ret[r] = _safe_copy(dat[k])\n return ret\n\n if isinstance(dat, (list, tuple)):\n return [_safe_copy(i) for i in dat]\n\n return dat\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a mongodb server
Required python modules: pymongo
This returner will send data from the minions to a MongoDB server. MongoDB
server can be configured by using host, port, db, user and password settings
or by connection string URI (for pymongo > 2.3). To configure the settings
for your MongoDB server, add the following lines to the minion config files:
.. code-block:: yaml
mongo.db: <database name>
mongo.host: <server ip address>
mongo.user: <MongoDB username>
mongo.password: <MongoDB user password>
mongo.port: 27017
Or single URI:
.. code-block:: yaml
mongo.uri: URI
where uri is in the format:
.. code-block:: text
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Example:
.. code-block:: text
mongodb://db1.example.net:27017/mydatabase
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000
More information on URI format can be found in
https://docs.mongodb.com/manual/reference/connection-string/
You can also ask for indexes creation on the most common used fields, which
should greatly improve performance. Indexes are not created by default.
.. code-block:: yaml
mongo.indexes: true
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.mongo.db: <database name>
alternative.mongo.host: <server ip address>
alternative.mongo.user: <MongoDB username>
alternative.mongo.password: <MongoDB user password>
alternative.mongo.port: 27017
Or single URI:
.. code-block:: yaml
alternative.mongo.uri: URI
This mongo returner is being developed to replace the default mongodb returner
in the future and should not be considered API stable yet.
To use the mongo returner, append '--return mongo' to the salt command.
.. code-block:: bash
salt '*' test.ping --return mongo
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.ext import six
from salt.utils.versions import LooseVersion as _LooseVersion
# Import third party libs
try:
import pymongo
PYMONGO_VERSION = _LooseVersion(pymongo.version)
HAS_PYMONGO = True
except ImportError:
HAS_PYMONGO = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'mongo'
def __virtual__():
if not HAS_PYMONGO:
return False, 'Could not import mongo returner; pymongo is not installed.'
return __virtualname__
def _remove_dots(src):
'''
Remove the dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
def _get_options(ret=None):
'''
Get the mongo options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password',
'indexes': 'indexes',
'uri': 'uri'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
uri = _options.get('uri')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if uri and PYMONGO_VERSION > _LooseVersion('2.3'):
if uri and host:
raise salt.exceptions.SaltConfigurationError(
"Mongo returner expects either uri or host configuration. Both were provided")
pymongo.uri_parser.parse_uri(uri)
conn = pymongo.MongoClient(uri)
mdb = conn.get_database()
else:
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
if uri:
raise salt.exceptions.SaltConfigurationError(
"pymongo <= 2.3 does not support uri format")
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
mdb.events.create_index('tag')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
mdb.events.ensure_index('tag')
return conn, mdb
def returner(ret):
'''
Return data to a mongodb server
'''
conn, mdb = _get_conn(ret)
if isinstance(ret['return'], dict):
back = _remove_dots(ret['return'])
else:
back = ret['return']
if isinstance(ret, dict):
full_ret = _remove_dots(ret)
else:
full_ret = ret
log.debug(back)
sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret}
if 'out' in ret:
sdata['out'] = ret['out']
# save returns in the saltReturns collection in the json format:
# { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>,
# 'fun': <function>, 'full_ret': <unformatted return with dots removed>}
#
# again we run into the issue with deprecated code from previous versions
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure that the original data is not changed, raising issue with pymongo team
mdb.saltReturns.insert_one(sdata.copy())
else:
mdb.saltReturns.insert(sdata.copy())
def _safe_copy(dat):
''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encodings,
\\ --> %5c
$ --> %24
. --> %2e
Which means also escaping '%':
% -> %25
'''
if isinstance(dat, dict):
ret = {}
for k in dat:
r = k.replace('%', '%25').replace('\\', '%5c').replace('$', '%24').replace('.', '%2e')
if r != k:
log.debug('converting dict key from %s to %s for mongodb', k, r)
ret[r] = _safe_copy(dat[k])
return ret
if isinstance(dat, (list, tuple)):
return [_safe_copy(i) for i in dat]
return dat
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load associated with a given job id
'''
conn, mdb = _get_conn(ret=None)
return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret
def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret
def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret
def get_jids():
'''
Return a list of job ids
'''
conn, mdb = _get_conn(ret=None)
map = "function() { emit(this.jid, this); }"
reduce = "function (key, values) { return values[0]; }"
result = mdb.jobs.inline_map_reduce(map, reduce)
ret = {}
for r in result:
jid = r['_id']
ret[jid] = salt.utils.jid.format_jid_instance(jid, r['value'])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def event_return(events):
'''
Return events to Mongodb server
'''
conn, mdb = _get_conn(ret=None)
if isinstance(events, list):
events = events[0]
if isinstance(events, dict):
log.debug(events)
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.events.insert_one(events.copy())
else:
mdb.events.insert(events.copy())
|
saltstack/salt
|
salt/returners/mongo_future_return.py
|
get_load
|
python
|
def get_load(jid):
'''
Return the load associated with a given job id
'''
conn, mdb = _get_conn(ret=None)
return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
|
Return the load associated with a given job id
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_future_return.py#L301-L306
|
[
"def _get_conn(ret):\n '''\n Return a mongodb connection object\n '''\n _options = _get_options(ret)\n\n host = _options.get('host')\n port = _options.get('port')\n uri = _options.get('uri')\n db_ = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n indexes = _options.get('indexes', False)\n\n # at some point we should remove support for\n # pymongo versions < 2.3 until then there are\n # a bunch of these sections that need to be supported\n if uri and PYMONGO_VERSION > _LooseVersion('2.3'):\n if uri and host:\n raise salt.exceptions.SaltConfigurationError(\n \"Mongo returner expects either uri or host configuration. Both were provided\")\n pymongo.uri_parser.parse_uri(uri)\n conn = pymongo.MongoClient(uri)\n mdb = conn.get_database()\n else:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n conn = pymongo.MongoClient(host, port)\n else:\n if uri:\n raise salt.exceptions.SaltConfigurationError(\n \"pymongo <= 2.3 does not support uri format\")\n conn = pymongo.Connection(host, port)\n\n mdb = conn[db_]\n if user and password:\n mdb.authenticate(user, password)\n\n if indexes:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n mdb.saltReturns.create_index('minion')\n mdb.saltReturns.create_index('jid')\n mdb.jobs.create_index('jid')\n mdb.events.create_index('tag')\n else:\n mdb.saltReturns.ensure_index('minion')\n mdb.saltReturns.ensure_index('jid')\n mdb.jobs.ensure_index('jid')\n mdb.events.ensure_index('tag')\n\n return conn, mdb\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a mongodb server
Required python modules: pymongo
This returner will send data from the minions to a MongoDB server. MongoDB
server can be configured by using host, port, db, user and password settings
or by connection string URI (for pymongo > 2.3). To configure the settings
for your MongoDB server, add the following lines to the minion config files:
.. code-block:: yaml
mongo.db: <database name>
mongo.host: <server ip address>
mongo.user: <MongoDB username>
mongo.password: <MongoDB user password>
mongo.port: 27017
Or single URI:
.. code-block:: yaml
mongo.uri: URI
where uri is in the format:
.. code-block:: text
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Example:
.. code-block:: text
mongodb://db1.example.net:27017/mydatabase
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000
More information on URI format can be found in
https://docs.mongodb.com/manual/reference/connection-string/
You can also ask for indexes creation on the most common used fields, which
should greatly improve performance. Indexes are not created by default.
.. code-block:: yaml
mongo.indexes: true
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.mongo.db: <database name>
alternative.mongo.host: <server ip address>
alternative.mongo.user: <MongoDB username>
alternative.mongo.password: <MongoDB user password>
alternative.mongo.port: 27017
Or single URI:
.. code-block:: yaml
alternative.mongo.uri: URI
This mongo returner is being developed to replace the default mongodb returner
in the future and should not be considered API stable yet.
To use the mongo returner, append '--return mongo' to the salt command.
.. code-block:: bash
salt '*' test.ping --return mongo
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.ext import six
from salt.utils.versions import LooseVersion as _LooseVersion
# Import third party libs
try:
import pymongo
PYMONGO_VERSION = _LooseVersion(pymongo.version)
HAS_PYMONGO = True
except ImportError:
HAS_PYMONGO = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'mongo'
def __virtual__():
if not HAS_PYMONGO:
return False, 'Could not import mongo returner; pymongo is not installed.'
return __virtualname__
def _remove_dots(src):
'''
Remove the dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
def _get_options(ret=None):
'''
Get the mongo options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password',
'indexes': 'indexes',
'uri': 'uri'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
uri = _options.get('uri')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if uri and PYMONGO_VERSION > _LooseVersion('2.3'):
if uri and host:
raise salt.exceptions.SaltConfigurationError(
"Mongo returner expects either uri or host configuration. Both were provided")
pymongo.uri_parser.parse_uri(uri)
conn = pymongo.MongoClient(uri)
mdb = conn.get_database()
else:
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
if uri:
raise salt.exceptions.SaltConfigurationError(
"pymongo <= 2.3 does not support uri format")
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
mdb.events.create_index('tag')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
mdb.events.ensure_index('tag')
return conn, mdb
def returner(ret):
'''
Return data to a mongodb server
'''
conn, mdb = _get_conn(ret)
if isinstance(ret['return'], dict):
back = _remove_dots(ret['return'])
else:
back = ret['return']
if isinstance(ret, dict):
full_ret = _remove_dots(ret)
else:
full_ret = ret
log.debug(back)
sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret}
if 'out' in ret:
sdata['out'] = ret['out']
# save returns in the saltReturns collection in the json format:
# { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>,
# 'fun': <function>, 'full_ret': <unformatted return with dots removed>}
#
# again we run into the issue with deprecated code from previous versions
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure that the original data is not changed, raising issue with pymongo team
mdb.saltReturns.insert_one(sdata.copy())
else:
mdb.saltReturns.insert(sdata.copy())
def _safe_copy(dat):
''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encodings,
\\ --> %5c
$ --> %24
. --> %2e
Which means also escaping '%':
% -> %25
'''
if isinstance(dat, dict):
ret = {}
for k in dat:
r = k.replace('%', '%25').replace('\\', '%5c').replace('$', '%24').replace('.', '%2e')
if r != k:
log.debug('converting dict key from %s to %s for mongodb', k, r)
ret[r] = _safe_copy(dat[k])
return ret
if isinstance(dat, (list, tuple)):
return [_safe_copy(i) for i in dat]
return dat
def save_load(jid, load, minions=None):
'''
Save the load for a given job id
'''
conn, mdb = _get_conn(ret=None)
to_save = _safe_copy(load)
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure original data for load is unchanged
mdb.jobs.insert_one(to_save)
else:
mdb.jobs.insert(to_save)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret
def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret
def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret
def get_jids():
'''
Return a list of job ids
'''
conn, mdb = _get_conn(ret=None)
map = "function() { emit(this.jid, this); }"
reduce = "function (key, values) { return values[0]; }"
result = mdb.jobs.inline_map_reduce(map, reduce)
ret = {}
for r in result:
jid = r['_id']
ret[jid] = salt.utils.jid.format_jid_instance(jid, r['value'])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def event_return(events):
'''
Return events to Mongodb server
'''
conn, mdb = _get_conn(ret=None)
if isinstance(events, list):
events = events[0]
if isinstance(events, dict):
log.debug(events)
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.events.insert_one(events.copy())
else:
mdb.events.insert(events.copy())
|
saltstack/salt
|
salt/returners/mongo_future_return.py
|
get_minions
|
python
|
def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret
|
Return a list of minions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_future_return.py#L336-L344
|
[
"def _get_conn(ret):\n '''\n Return a mongodb connection object\n '''\n _options = _get_options(ret)\n\n host = _options.get('host')\n port = _options.get('port')\n uri = _options.get('uri')\n db_ = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n indexes = _options.get('indexes', False)\n\n # at some point we should remove support for\n # pymongo versions < 2.3 until then there are\n # a bunch of these sections that need to be supported\n if uri and PYMONGO_VERSION > _LooseVersion('2.3'):\n if uri and host:\n raise salt.exceptions.SaltConfigurationError(\n \"Mongo returner expects either uri or host configuration. Both were provided\")\n pymongo.uri_parser.parse_uri(uri)\n conn = pymongo.MongoClient(uri)\n mdb = conn.get_database()\n else:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n conn = pymongo.MongoClient(host, port)\n else:\n if uri:\n raise salt.exceptions.SaltConfigurationError(\n \"pymongo <= 2.3 does not support uri format\")\n conn = pymongo.Connection(host, port)\n\n mdb = conn[db_]\n if user and password:\n mdb.authenticate(user, password)\n\n if indexes:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n mdb.saltReturns.create_index('minion')\n mdb.saltReturns.create_index('jid')\n mdb.jobs.create_index('jid')\n mdb.events.create_index('tag')\n else:\n mdb.saltReturns.ensure_index('minion')\n mdb.saltReturns.ensure_index('jid')\n mdb.jobs.ensure_index('jid')\n mdb.events.ensure_index('tag')\n\n return conn, mdb\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a mongodb server
Required python modules: pymongo
This returner will send data from the minions to a MongoDB server. MongoDB
server can be configured by using host, port, db, user and password settings
or by connection string URI (for pymongo > 2.3). To configure the settings
for your MongoDB server, add the following lines to the minion config files:
.. code-block:: yaml
mongo.db: <database name>
mongo.host: <server ip address>
mongo.user: <MongoDB username>
mongo.password: <MongoDB user password>
mongo.port: 27017
Or single URI:
.. code-block:: yaml
mongo.uri: URI
where uri is in the format:
.. code-block:: text
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Example:
.. code-block:: text
mongodb://db1.example.net:27017/mydatabase
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000
More information on URI format can be found in
https://docs.mongodb.com/manual/reference/connection-string/
You can also ask for indexes creation on the most common used fields, which
should greatly improve performance. Indexes are not created by default.
.. code-block:: yaml
mongo.indexes: true
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.mongo.db: <database name>
alternative.mongo.host: <server ip address>
alternative.mongo.user: <MongoDB username>
alternative.mongo.password: <MongoDB user password>
alternative.mongo.port: 27017
Or single URI:
.. code-block:: yaml
alternative.mongo.uri: URI
This mongo returner is being developed to replace the default mongodb returner
in the future and should not be considered API stable yet.
To use the mongo returner, append '--return mongo' to the salt command.
.. code-block:: bash
salt '*' test.ping --return mongo
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.ext import six
from salt.utils.versions import LooseVersion as _LooseVersion
# Import third party libs
try:
import pymongo
PYMONGO_VERSION = _LooseVersion(pymongo.version)
HAS_PYMONGO = True
except ImportError:
HAS_PYMONGO = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'mongo'
def __virtual__():
if not HAS_PYMONGO:
return False, 'Could not import mongo returner; pymongo is not installed.'
return __virtualname__
def _remove_dots(src):
'''
Remove the dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
def _get_options(ret=None):
'''
Get the mongo options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password',
'indexes': 'indexes',
'uri': 'uri'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
uri = _options.get('uri')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if uri and PYMONGO_VERSION > _LooseVersion('2.3'):
if uri and host:
raise salt.exceptions.SaltConfigurationError(
"Mongo returner expects either uri or host configuration. Both were provided")
pymongo.uri_parser.parse_uri(uri)
conn = pymongo.MongoClient(uri)
mdb = conn.get_database()
else:
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
if uri:
raise salt.exceptions.SaltConfigurationError(
"pymongo <= 2.3 does not support uri format")
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
mdb.events.create_index('tag')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
mdb.events.ensure_index('tag')
return conn, mdb
def returner(ret):
'''
Return data to a mongodb server
'''
conn, mdb = _get_conn(ret)
if isinstance(ret['return'], dict):
back = _remove_dots(ret['return'])
else:
back = ret['return']
if isinstance(ret, dict):
full_ret = _remove_dots(ret)
else:
full_ret = ret
log.debug(back)
sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret}
if 'out' in ret:
sdata['out'] = ret['out']
# save returns in the saltReturns collection in the json format:
# { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>,
# 'fun': <function>, 'full_ret': <unformatted return with dots removed>}
#
# again we run into the issue with deprecated code from previous versions
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure that the original data is not changed, raising issue with pymongo team
mdb.saltReturns.insert_one(sdata.copy())
else:
mdb.saltReturns.insert(sdata.copy())
def _safe_copy(dat):
''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encodings,
\\ --> %5c
$ --> %24
. --> %2e
Which means also escaping '%':
% -> %25
'''
if isinstance(dat, dict):
ret = {}
for k in dat:
r = k.replace('%', '%25').replace('\\', '%5c').replace('$', '%24').replace('.', '%2e')
if r != k:
log.debug('converting dict key from %s to %s for mongodb', k, r)
ret[r] = _safe_copy(dat[k])
return ret
if isinstance(dat, (list, tuple)):
return [_safe_copy(i) for i in dat]
return dat
def save_load(jid, load, minions=None):
'''
Save the load for a given job id
'''
conn, mdb = _get_conn(ret=None)
to_save = _safe_copy(load)
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure original data for load is unchanged
mdb.jobs.insert_one(to_save)
else:
mdb.jobs.insert(to_save)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load associated with a given job id
'''
conn, mdb = _get_conn(ret=None)
return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret
def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret
def get_jids():
'''
Return a list of job ids
'''
conn, mdb = _get_conn(ret=None)
map = "function() { emit(this.jid, this); }"
reduce = "function (key, values) { return values[0]; }"
result = mdb.jobs.inline_map_reduce(map, reduce)
ret = {}
for r in result:
jid = r['_id']
ret[jid] = salt.utils.jid.format_jid_instance(jid, r['value'])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def event_return(events):
'''
Return events to Mongodb server
'''
conn, mdb = _get_conn(ret=None)
if isinstance(events, list):
events = events[0]
if isinstance(events, dict):
log.debug(events)
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.events.insert_one(events.copy())
else:
mdb.events.insert(events.copy())
|
saltstack/salt
|
salt/returners/mongo_future_return.py
|
get_jids
|
python
|
def get_jids():
'''
Return a list of job ids
'''
conn, mdb = _get_conn(ret=None)
map = "function() { emit(this.jid, this); }"
reduce = "function (key, values) { return values[0]; }"
result = mdb.jobs.inline_map_reduce(map, reduce)
ret = {}
for r in result:
jid = r['_id']
ret[jid] = salt.utils.jid.format_jid_instance(jid, r['value'])
return ret
|
Return a list of job ids
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_future_return.py#L347-L359
|
[
"def _get_conn(ret):\n '''\n Return a mongodb connection object\n '''\n _options = _get_options(ret)\n\n host = _options.get('host')\n port = _options.get('port')\n uri = _options.get('uri')\n db_ = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n indexes = _options.get('indexes', False)\n\n # at some point we should remove support for\n # pymongo versions < 2.3 until then there are\n # a bunch of these sections that need to be supported\n if uri and PYMONGO_VERSION > _LooseVersion('2.3'):\n if uri and host:\n raise salt.exceptions.SaltConfigurationError(\n \"Mongo returner expects either uri or host configuration. Both were provided\")\n pymongo.uri_parser.parse_uri(uri)\n conn = pymongo.MongoClient(uri)\n mdb = conn.get_database()\n else:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n conn = pymongo.MongoClient(host, port)\n else:\n if uri:\n raise salt.exceptions.SaltConfigurationError(\n \"pymongo <= 2.3 does not support uri format\")\n conn = pymongo.Connection(host, port)\n\n mdb = conn[db_]\n if user and password:\n mdb.authenticate(user, password)\n\n if indexes:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n mdb.saltReturns.create_index('minion')\n mdb.saltReturns.create_index('jid')\n mdb.jobs.create_index('jid')\n mdb.events.create_index('tag')\n else:\n mdb.saltReturns.ensure_index('minion')\n mdb.saltReturns.ensure_index('jid')\n mdb.jobs.ensure_index('jid')\n mdb.events.ensure_index('tag')\n\n return conn, mdb\n",
"def format_jid_instance(jid, job):\n '''\n Format the jid correctly\n '''\n ret = format_job_instance(job)\n ret.update({'StartTime': jid_to_time(jid)})\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a mongodb server
Required python modules: pymongo
This returner will send data from the minions to a MongoDB server. MongoDB
server can be configured by using host, port, db, user and password settings
or by connection string URI (for pymongo > 2.3). To configure the settings
for your MongoDB server, add the following lines to the minion config files:
.. code-block:: yaml
mongo.db: <database name>
mongo.host: <server ip address>
mongo.user: <MongoDB username>
mongo.password: <MongoDB user password>
mongo.port: 27017
Or single URI:
.. code-block:: yaml
mongo.uri: URI
where uri is in the format:
.. code-block:: text
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Example:
.. code-block:: text
mongodb://db1.example.net:27017/mydatabase
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000
More information on URI format can be found in
https://docs.mongodb.com/manual/reference/connection-string/
You can also ask for indexes creation on the most common used fields, which
should greatly improve performance. Indexes are not created by default.
.. code-block:: yaml
mongo.indexes: true
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.mongo.db: <database name>
alternative.mongo.host: <server ip address>
alternative.mongo.user: <MongoDB username>
alternative.mongo.password: <MongoDB user password>
alternative.mongo.port: 27017
Or single URI:
.. code-block:: yaml
alternative.mongo.uri: URI
This mongo returner is being developed to replace the default mongodb returner
in the future and should not be considered API stable yet.
To use the mongo returner, append '--return mongo' to the salt command.
.. code-block:: bash
salt '*' test.ping --return mongo
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.ext import six
from salt.utils.versions import LooseVersion as _LooseVersion
# Import third party libs
try:
import pymongo
PYMONGO_VERSION = _LooseVersion(pymongo.version)
HAS_PYMONGO = True
except ImportError:
HAS_PYMONGO = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'mongo'
def __virtual__():
if not HAS_PYMONGO:
return False, 'Could not import mongo returner; pymongo is not installed.'
return __virtualname__
def _remove_dots(src):
'''
Remove the dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
def _get_options(ret=None):
'''
Get the mongo options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password',
'indexes': 'indexes',
'uri': 'uri'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
uri = _options.get('uri')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if uri and PYMONGO_VERSION > _LooseVersion('2.3'):
if uri and host:
raise salt.exceptions.SaltConfigurationError(
"Mongo returner expects either uri or host configuration. Both were provided")
pymongo.uri_parser.parse_uri(uri)
conn = pymongo.MongoClient(uri)
mdb = conn.get_database()
else:
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
if uri:
raise salt.exceptions.SaltConfigurationError(
"pymongo <= 2.3 does not support uri format")
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
mdb.events.create_index('tag')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
mdb.events.ensure_index('tag')
return conn, mdb
def returner(ret):
'''
Return data to a mongodb server
'''
conn, mdb = _get_conn(ret)
if isinstance(ret['return'], dict):
back = _remove_dots(ret['return'])
else:
back = ret['return']
if isinstance(ret, dict):
full_ret = _remove_dots(ret)
else:
full_ret = ret
log.debug(back)
sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret}
if 'out' in ret:
sdata['out'] = ret['out']
# save returns in the saltReturns collection in the json format:
# { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>,
# 'fun': <function>, 'full_ret': <unformatted return with dots removed>}
#
# again we run into the issue with deprecated code from previous versions
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure that the original data is not changed, raising issue with pymongo team
mdb.saltReturns.insert_one(sdata.copy())
else:
mdb.saltReturns.insert(sdata.copy())
def _safe_copy(dat):
''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encodings,
\\ --> %5c
$ --> %24
. --> %2e
Which means also escaping '%':
% -> %25
'''
if isinstance(dat, dict):
ret = {}
for k in dat:
r = k.replace('%', '%25').replace('\\', '%5c').replace('$', '%24').replace('.', '%2e')
if r != k:
log.debug('converting dict key from %s to %s for mongodb', k, r)
ret[r] = _safe_copy(dat[k])
return ret
if isinstance(dat, (list, tuple)):
return [_safe_copy(i) for i in dat]
return dat
def save_load(jid, load, minions=None):
'''
Save the load for a given job id
'''
conn, mdb = _get_conn(ret=None)
to_save = _safe_copy(load)
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure original data for load is unchanged
mdb.jobs.insert_one(to_save)
else:
mdb.jobs.insert(to_save)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load associated with a given job id
'''
conn, mdb = _get_conn(ret=None)
return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret
def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret
def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def event_return(events):
'''
Return events to Mongodb server
'''
conn, mdb = _get_conn(ret=None)
if isinstance(events, list):
events = events[0]
if isinstance(events, dict):
log.debug(events)
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.events.insert_one(events.copy())
else:
mdb.events.insert(events.copy())
|
saltstack/salt
|
salt/returners/mongo_future_return.py
|
event_return
|
python
|
def event_return(events):
'''
Return events to Mongodb server
'''
conn, mdb = _get_conn(ret=None)
if isinstance(events, list):
events = events[0]
if isinstance(events, dict):
log.debug(events)
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.events.insert_one(events.copy())
else:
mdb.events.insert(events.copy())
|
Return events to Mongodb server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_future_return.py#L369-L384
|
[
"def _get_conn(ret):\n '''\n Return a mongodb connection object\n '''\n _options = _get_options(ret)\n\n host = _options.get('host')\n port = _options.get('port')\n uri = _options.get('uri')\n db_ = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n indexes = _options.get('indexes', False)\n\n # at some point we should remove support for\n # pymongo versions < 2.3 until then there are\n # a bunch of these sections that need to be supported\n if uri and PYMONGO_VERSION > _LooseVersion('2.3'):\n if uri and host:\n raise salt.exceptions.SaltConfigurationError(\n \"Mongo returner expects either uri or host configuration. Both were provided\")\n pymongo.uri_parser.parse_uri(uri)\n conn = pymongo.MongoClient(uri)\n mdb = conn.get_database()\n else:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n conn = pymongo.MongoClient(host, port)\n else:\n if uri:\n raise salt.exceptions.SaltConfigurationError(\n \"pymongo <= 2.3 does not support uri format\")\n conn = pymongo.Connection(host, port)\n\n mdb = conn[db_]\n if user and password:\n mdb.authenticate(user, password)\n\n if indexes:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n mdb.saltReturns.create_index('minion')\n mdb.saltReturns.create_index('jid')\n mdb.jobs.create_index('jid')\n mdb.events.create_index('tag')\n else:\n mdb.saltReturns.ensure_index('minion')\n mdb.saltReturns.ensure_index('jid')\n mdb.jobs.ensure_index('jid')\n mdb.events.ensure_index('tag')\n\n return conn, mdb\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a mongodb server
Required python modules: pymongo
This returner will send data from the minions to a MongoDB server. MongoDB
server can be configured by using host, port, db, user and password settings
or by connection string URI (for pymongo > 2.3). To configure the settings
for your MongoDB server, add the following lines to the minion config files:
.. code-block:: yaml
mongo.db: <database name>
mongo.host: <server ip address>
mongo.user: <MongoDB username>
mongo.password: <MongoDB user password>
mongo.port: 27017
Or single URI:
.. code-block:: yaml
mongo.uri: URI
where uri is in the format:
.. code-block:: text
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Example:
.. code-block:: text
mongodb://db1.example.net:27017/mydatabase
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000
More information on URI format can be found in
https://docs.mongodb.com/manual/reference/connection-string/
You can also ask for indexes creation on the most common used fields, which
should greatly improve performance. Indexes are not created by default.
.. code-block:: yaml
mongo.indexes: true
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.mongo.db: <database name>
alternative.mongo.host: <server ip address>
alternative.mongo.user: <MongoDB username>
alternative.mongo.password: <MongoDB user password>
alternative.mongo.port: 27017
Or single URI:
.. code-block:: yaml
alternative.mongo.uri: URI
This mongo returner is being developed to replace the default mongodb returner
in the future and should not be considered API stable yet.
To use the mongo returner, append '--return mongo' to the salt command.
.. code-block:: bash
salt '*' test.ping --return mongo
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
from salt.ext import six
from salt.utils.versions import LooseVersion as _LooseVersion
# Import third party libs
try:
import pymongo
PYMONGO_VERSION = _LooseVersion(pymongo.version)
HAS_PYMONGO = True
except ImportError:
HAS_PYMONGO = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'mongo'
def __virtual__():
if not HAS_PYMONGO:
return False, 'Could not import mongo returner; pymongo is not installed.'
return __virtualname__
def _remove_dots(src):
'''
Remove the dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
def _get_options(ret=None):
'''
Get the mongo options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'db': 'db',
'user': 'user',
'password': 'password',
'indexes': 'indexes',
'uri': 'uri'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
uri = _options.get('uri')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if uri and PYMONGO_VERSION > _LooseVersion('2.3'):
if uri and host:
raise salt.exceptions.SaltConfigurationError(
"Mongo returner expects either uri or host configuration. Both were provided")
pymongo.uri_parser.parse_uri(uri)
conn = pymongo.MongoClient(uri)
mdb = conn.get_database()
else:
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
if uri:
raise salt.exceptions.SaltConfigurationError(
"pymongo <= 2.3 does not support uri format")
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
mdb.events.create_index('tag')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
mdb.events.ensure_index('tag')
return conn, mdb
def returner(ret):
'''
Return data to a mongodb server
'''
conn, mdb = _get_conn(ret)
if isinstance(ret['return'], dict):
back = _remove_dots(ret['return'])
else:
back = ret['return']
if isinstance(ret, dict):
full_ret = _remove_dots(ret)
else:
full_ret = ret
log.debug(back)
sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret}
if 'out' in ret:
sdata['out'] = ret['out']
# save returns in the saltReturns collection in the json format:
# { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>,
# 'fun': <function>, 'full_ret': <unformatted return with dots removed>}
#
# again we run into the issue with deprecated code from previous versions
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure that the original data is not changed, raising issue with pymongo team
mdb.saltReturns.insert_one(sdata.copy())
else:
mdb.saltReturns.insert(sdata.copy())
def _safe_copy(dat):
''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encodings,
\\ --> %5c
$ --> %24
. --> %2e
Which means also escaping '%':
% -> %25
'''
if isinstance(dat, dict):
ret = {}
for k in dat:
r = k.replace('%', '%25').replace('\\', '%5c').replace('$', '%24').replace('.', '%2e')
if r != k:
log.debug('converting dict key from %s to %s for mongodb', k, r)
ret[r] = _safe_copy(dat[k])
return ret
if isinstance(dat, (list, tuple)):
return [_safe_copy(i) for i in dat]
return dat
def save_load(jid, load, minions=None):
'''
Save the load for a given job id
'''
conn, mdb = _get_conn(ret=None)
to_save = _safe_copy(load)
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure original data for load is unchanged
mdb.jobs.insert_one(to_save)
else:
mdb.jobs.insert(to_save)
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load associated with a given job id
'''
conn, mdb = _get_conn(ret=None)
return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret
def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret
def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret
def get_jids():
'''
Return a list of job ids
'''
conn, mdb = _get_conn(ret=None)
map = "function() { emit(this.jid, this); }"
reduce = "function (key, values) { return values[0]; }"
result = mdb.jobs.inline_map_reduce(map, reduce)
ret = {}
for r in result:
jid = r['_id']
ret[jid] = salt.utils.jid.format_jid_instance(jid, r['value'])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
lowstate_file_refs
|
python
|
def lowstate_file_refs(chunks):
'''
Create a list of file ref objects to reconcile
'''
refs = {}
for chunk in chunks:
saltenv = 'base'
crefs = []
for state in chunk:
if state == '__env__':
saltenv = chunk[state]
elif state == 'saltenv':
saltenv = chunk[state]
elif state.startswith('__'):
continue
crefs.extend(salt_refs(chunk[state]))
if crefs:
if saltenv not in refs:
refs[saltenv] = []
refs[saltenv].append(crefs)
return refs
|
Create a list of file ref objects to reconcile
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L1535-L1555
|
[
"def salt_refs(data):\n '''\n Pull salt file references out of the states\n '''\n proto = 'salt://'\n ret = []\n if isinstance(data, six.string_types):\n if data.startswith(proto):\n return [data]\n if isinstance(data, list):\n for comp in data:\n if isinstance(comp, six.string_types):\n if comp.startswith(proto):\n ret.append(comp)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Create ssh executor system
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import copy
import getpass
import logging
import multiprocessing
import subprocess
import hashlib
import tarfile
import os
import re
import sys
import time
import uuid
import tempfile
import binascii
import sys
import datetime
# Import salt libs
import salt.output
import salt.client.ssh.shell
import salt.client.ssh.wrapper
import salt.config
import salt.exceptions
import salt.defaults.exitcodes
import salt.log
import salt.loader
import salt.minion
import salt.roster
import salt.serializers.yaml
import salt.state
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.json
import salt.utils.network
import salt.utils.path
import salt.utils.stringutils
import salt.utils.thin
import salt.utils.url
import salt.utils.verify
from salt.utils.platform import is_windows
from salt.utils.process import MultiprocessingProcess
import salt.roster
from salt.template import compile_template
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin
try:
import saltwinshell
HAS_WINSHELL = True
except ImportError:
HAS_WINSHELL = False
from salt.utils.zeromq import zmq
# The directory where salt thin is deployed
DEFAULT_THIN_DIR = '/var/tmp/.%%USER%%_%%FQDNUUID%%_salt'
# RSTR is just a delimiter to distinguish the beginning of salt STDOUT
# and STDERR. There is no special meaning. Messages prior to RSTR in
# stderr and stdout are either from SSH or from the shim.
#
# RSTR on both stdout and stderr:
# no errors in SHIM - output after RSTR is from salt
# No RSTR in stderr, RSTR in stdout:
# no errors in SSH_SH_SHIM, but SHIM commands for salt master are after
# RSTR in stdout
# No RSTR in stderr, no RSTR in stdout:
# Failure in SHIM
# RSTR in stderr, No RSTR in stdout:
# Undefined behavior
RSTR = '_edbc7885e4f9aac9b83b35999b68d015148caf467b78fa39c05f669c0ff89878'
# The regex to find RSTR in output - Must be on an output line by itself
# NOTE - must use non-grouping match groups or output splitting will fail.
RSTR_RE = r'(?:^|\r?\n)' + RSTR + r'(?:\r?\n|$)'
# METHODOLOGY:
#
# 1) Make the _thinnest_ /bin/sh shim (SSH_SH_SHIM) to find the python
# interpreter and get it invoked
# 2) Once a qualified python is found start it with the SSH_PY_SHIM
# 3) The shim is converted to a single semicolon separated line, so
# some constructs are needed to keep it clean.
# NOTE:
# * SSH_SH_SHIM is generic and can be used to load+exec *any* python
# script on the target.
# * SSH_PY_SHIM is in a separate file rather than stuffed in a string
# in salt/client/ssh/__init__.py - this makes testing *easy* because
# it can be invoked directly.
# * SSH_PY_SHIM is base64 encoded and formatted into the SSH_SH_SHIM
# string. This makes the python script "armored" so that it can
# all be passed in the SSH command and will not need special quoting
# (which likely would be impossibe to do anyway)
# * The formatted SSH_SH_SHIM with the SSH_PY_SHIM payload is a bit
# big (~7.5k). If this proves problematic for an SSH command we
# might try simply invoking "/bin/sh -s" and passing the formatted
# SSH_SH_SHIM on SSH stdin.
# NOTE: there are two passes of formatting:
# 1) Substitute in static values
# - EX_THIN_PYTHON_INVALID - exit code if a suitable python is not found
# 2) Substitute in instance-specific commands
# - DEBUG - enable shim debugging (any non-zero string enables)
# - SUDO - load python and execute as root (any non-zero string enables)
# - SSH_PY_CODE - base64-encoded python code to execute
# - SSH_PY_ARGS - arguments to pass to python code
# This shim generically loads python code . . . and *no* more.
# - Uses /bin/sh for maximum compatibility - then jumps to
# python for ultra-maximum compatibility.
#
# 1. Identify a suitable python
# 2. Jump to python
# Note the list-comprehension syntax to define SSH_SH_SHIM is needed
# to be able to define the string with indentation for readability but
# still strip the white space for compactness and to avoid issues with
# some multi-line embedded python code having indentation errors
SSH_SH_SHIM = \
'\n'.join(
[s.strip() for s in r'''/bin/sh << 'EOF'
set -e
set -u
DEBUG="{{DEBUG}}"
if [ -n "$DEBUG" ]
then set -x
fi
SUDO=""
if [ -n "{{SUDO}}" ]
then SUDO="sudo "
fi
SUDO_USER="{{SUDO_USER}}"
if [ "$SUDO" ] && [ "$SUDO_USER" ]
then SUDO="sudo -u {{SUDO_USER}}"
elif [ "$SUDO" ] && [ -n "$SUDO_USER" ]
then SUDO="sudo "
fi
EX_PYTHON_INVALID={EX_THIN_PYTHON_INVALID}
PYTHON_CMDS="python3 python27 python2.7 python26 python2.6 python2 python"
for py_cmd in $PYTHON_CMDS
do
if command -v "$py_cmd" >/dev/null 2>&1 && "$py_cmd" -c "import sys; sys.exit(not (sys.version_info >= (2, 6)));"
then
py_cmd_path=`"$py_cmd" -c 'from __future__ import print_function;import sys; print(sys.executable);'`
cmdpath=`command -v $py_cmd 2>/dev/null || which $py_cmd 2>/dev/null`
if file $cmdpath | grep "shell script" > /dev/null
then
ex_vars="'PATH', 'LD_LIBRARY_PATH', 'MANPATH', \
'XDG_DATA_DIRS', 'PKG_CONFIG_PATH'"
export `$py_cmd -c \
"from __future__ import print_function;
import sys;
import os;
map(sys.stdout.write, ['{{{{0}}}}={{{{1}}}} ' \
.format(x, os.environ[x]) for x in [$ex_vars]])"`
exec $SUDO PATH=$PATH LD_LIBRARY_PATH=$LD_LIBRARY_PATH \
MANPATH=$MANPATH XDG_DATA_DIRS=$XDG_DATA_DIRS \
PKG_CONFIG_PATH=$PKG_CONFIG_PATH \
"$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
else
exec $SUDO "$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
fi
exit 0
else
continue
fi
done
echo "ERROR: Unable to locate appropriate python command" >&2
exit $EX_PYTHON_INVALID
EOF'''.format(
EX_THIN_PYTHON_INVALID=salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,
).split('\n')])
if not is_windows():
shim_file = os.path.join(os.path.dirname(__file__), 'ssh_py_shim.py')
if not os.path.exists(shim_file):
# On esky builds we only have the .pyc file
shim_file += 'c'
with salt.utils.files.fopen(shim_file) as ssh_py_shim:
SSH_PY_SHIM = ssh_py_shim.read()
log = logging.getLogger(__name__)
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
def salt_refs(data):
'''
Pull salt file references out of the states
'''
proto = 'salt://'
ret = []
if isinstance(data, six.string_types):
if data.startswith(proto):
return [data]
if isinstance(data, list):
for comp in data:
if isinstance(comp, six.string_types):
if comp.startswith(proto):
ret.append(comp)
return ret
def mod_data(fsclient):
'''
Generate the module arguments for the shim data
'''
# TODO, change out for a fileserver backend
sync_refs = [
'modules',
'states',
'grains',
'renderers',
'returners',
]
ret = {}
envs = fsclient.envs()
ver_base = ''
for env in envs:
files = fsclient.file_list(env)
for ref in sync_refs:
mods_data = {}
pref = '_{0}'.format(ref)
for fn_ in sorted(files):
if fn_.startswith(pref):
if fn_.endswith(('.py', '.so', '.pyx')):
full = salt.utils.url.create(fn_)
mod_path = fsclient.cache_file(full, env)
if not os.path.isfile(mod_path):
continue
mods_data[os.path.basename(fn_)] = mod_path
chunk = salt.utils.hashutils.get_hash(mod_path)
ver_base += chunk
if mods_data:
if ref in ret:
ret[ref].update(mods_data)
else:
ret[ref] = mods_data
if not ret:
return {}
if six.PY3:
ver_base = salt.utils.stringutils.to_bytes(ver_base)
ver = hashlib.sha1(ver_base).hexdigest()
ext_tar_path = os.path.join(
fsclient.opts['cachedir'],
'ext_mods.{0}.tgz'.format(ver))
mods = {'version': ver,
'file': ext_tar_path}
if os.path.isfile(ext_tar_path):
return mods
tfp = tarfile.open(ext_tar_path, 'w:gz')
verfile = os.path.join(fsclient.opts['cachedir'], 'ext_mods.ver')
with salt.utils.files.fopen(verfile, 'w+') as fp_:
fp_.write(ver)
tfp.add(verfile, 'ext_version')
for ref in ret:
for fn_ in ret[ref]:
tfp.add(ret[ref][fn_], os.path.join(ref, fn_))
tfp.close()
return mods
def ssh_version():
'''
Returns the version of the installed ssh command
'''
# This function needs more granular checks and to be validated against
# older versions of ssh
ret = subprocess.Popen(
['ssh', '-V'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
try:
version_parts = ret[1].split(b',')[0].split(b'_')[1]
parts = []
for part in version_parts:
try:
parts.append(int(part))
except ValueError:
return tuple(parts)
return tuple(parts)
except IndexError:
return (2, 0)
def _convert_args(args):
'''
Take a list of args, and convert any dicts inside the list to keyword
args in the form of `key=value`, ready to be passed to salt-ssh
'''
converted = []
for arg in args:
if isinstance(arg, dict):
for key in list(arg.keys()):
if key == '__kwarg__':
continue
converted.append('{0}={1}'.format(key, arg[key]))
else:
converted.append(arg)
return converted
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
salt_refs
|
python
|
def salt_refs(data):
'''
Pull salt file references out of the states
'''
proto = 'salt://'
ret = []
if isinstance(data, six.string_types):
if data.startswith(proto):
return [data]
if isinstance(data, list):
for comp in data:
if isinstance(comp, six.string_types):
if comp.startswith(proto):
ret.append(comp)
return ret
|
Pull salt file references out of the states
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L1558-L1572
| null |
# -*- coding: utf-8 -*-
'''
Create ssh executor system
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import copy
import getpass
import logging
import multiprocessing
import subprocess
import hashlib
import tarfile
import os
import re
import sys
import time
import uuid
import tempfile
import binascii
import sys
import datetime
# Import salt libs
import salt.output
import salt.client.ssh.shell
import salt.client.ssh.wrapper
import salt.config
import salt.exceptions
import salt.defaults.exitcodes
import salt.log
import salt.loader
import salt.minion
import salt.roster
import salt.serializers.yaml
import salt.state
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.json
import salt.utils.network
import salt.utils.path
import salt.utils.stringutils
import salt.utils.thin
import salt.utils.url
import salt.utils.verify
from salt.utils.platform import is_windows
from salt.utils.process import MultiprocessingProcess
import salt.roster
from salt.template import compile_template
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin
try:
import saltwinshell
HAS_WINSHELL = True
except ImportError:
HAS_WINSHELL = False
from salt.utils.zeromq import zmq
# The directory where salt thin is deployed
DEFAULT_THIN_DIR = '/var/tmp/.%%USER%%_%%FQDNUUID%%_salt'
# RSTR is just a delimiter to distinguish the beginning of salt STDOUT
# and STDERR. There is no special meaning. Messages prior to RSTR in
# stderr and stdout are either from SSH or from the shim.
#
# RSTR on both stdout and stderr:
# no errors in SHIM - output after RSTR is from salt
# No RSTR in stderr, RSTR in stdout:
# no errors in SSH_SH_SHIM, but SHIM commands for salt master are after
# RSTR in stdout
# No RSTR in stderr, no RSTR in stdout:
# Failure in SHIM
# RSTR in stderr, No RSTR in stdout:
# Undefined behavior
RSTR = '_edbc7885e4f9aac9b83b35999b68d015148caf467b78fa39c05f669c0ff89878'
# The regex to find RSTR in output - Must be on an output line by itself
# NOTE - must use non-grouping match groups or output splitting will fail.
RSTR_RE = r'(?:^|\r?\n)' + RSTR + r'(?:\r?\n|$)'
# METHODOLOGY:
#
# 1) Make the _thinnest_ /bin/sh shim (SSH_SH_SHIM) to find the python
# interpreter and get it invoked
# 2) Once a qualified python is found start it with the SSH_PY_SHIM
# 3) The shim is converted to a single semicolon separated line, so
# some constructs are needed to keep it clean.
# NOTE:
# * SSH_SH_SHIM is generic and can be used to load+exec *any* python
# script on the target.
# * SSH_PY_SHIM is in a separate file rather than stuffed in a string
# in salt/client/ssh/__init__.py - this makes testing *easy* because
# it can be invoked directly.
# * SSH_PY_SHIM is base64 encoded and formatted into the SSH_SH_SHIM
# string. This makes the python script "armored" so that it can
# all be passed in the SSH command and will not need special quoting
# (which likely would be impossibe to do anyway)
# * The formatted SSH_SH_SHIM with the SSH_PY_SHIM payload is a bit
# big (~7.5k). If this proves problematic for an SSH command we
# might try simply invoking "/bin/sh -s" and passing the formatted
# SSH_SH_SHIM on SSH stdin.
# NOTE: there are two passes of formatting:
# 1) Substitute in static values
# - EX_THIN_PYTHON_INVALID - exit code if a suitable python is not found
# 2) Substitute in instance-specific commands
# - DEBUG - enable shim debugging (any non-zero string enables)
# - SUDO - load python and execute as root (any non-zero string enables)
# - SSH_PY_CODE - base64-encoded python code to execute
# - SSH_PY_ARGS - arguments to pass to python code
# This shim generically loads python code . . . and *no* more.
# - Uses /bin/sh for maximum compatibility - then jumps to
# python for ultra-maximum compatibility.
#
# 1. Identify a suitable python
# 2. Jump to python
# Note the list-comprehension syntax to define SSH_SH_SHIM is needed
# to be able to define the string with indentation for readability but
# still strip the white space for compactness and to avoid issues with
# some multi-line embedded python code having indentation errors
SSH_SH_SHIM = \
'\n'.join(
[s.strip() for s in r'''/bin/sh << 'EOF'
set -e
set -u
DEBUG="{{DEBUG}}"
if [ -n "$DEBUG" ]
then set -x
fi
SUDO=""
if [ -n "{{SUDO}}" ]
then SUDO="sudo "
fi
SUDO_USER="{{SUDO_USER}}"
if [ "$SUDO" ] && [ "$SUDO_USER" ]
then SUDO="sudo -u {{SUDO_USER}}"
elif [ "$SUDO" ] && [ -n "$SUDO_USER" ]
then SUDO="sudo "
fi
EX_PYTHON_INVALID={EX_THIN_PYTHON_INVALID}
PYTHON_CMDS="python3 python27 python2.7 python26 python2.6 python2 python"
for py_cmd in $PYTHON_CMDS
do
if command -v "$py_cmd" >/dev/null 2>&1 && "$py_cmd" -c "import sys; sys.exit(not (sys.version_info >= (2, 6)));"
then
py_cmd_path=`"$py_cmd" -c 'from __future__ import print_function;import sys; print(sys.executable);'`
cmdpath=`command -v $py_cmd 2>/dev/null || which $py_cmd 2>/dev/null`
if file $cmdpath | grep "shell script" > /dev/null
then
ex_vars="'PATH', 'LD_LIBRARY_PATH', 'MANPATH', \
'XDG_DATA_DIRS', 'PKG_CONFIG_PATH'"
export `$py_cmd -c \
"from __future__ import print_function;
import sys;
import os;
map(sys.stdout.write, ['{{{{0}}}}={{{{1}}}} ' \
.format(x, os.environ[x]) for x in [$ex_vars]])"`
exec $SUDO PATH=$PATH LD_LIBRARY_PATH=$LD_LIBRARY_PATH \
MANPATH=$MANPATH XDG_DATA_DIRS=$XDG_DATA_DIRS \
PKG_CONFIG_PATH=$PKG_CONFIG_PATH \
"$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
else
exec $SUDO "$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
fi
exit 0
else
continue
fi
done
echo "ERROR: Unable to locate appropriate python command" >&2
exit $EX_PYTHON_INVALID
EOF'''.format(
EX_THIN_PYTHON_INVALID=salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,
).split('\n')])
if not is_windows():
shim_file = os.path.join(os.path.dirname(__file__), 'ssh_py_shim.py')
if not os.path.exists(shim_file):
# On esky builds we only have the .pyc file
shim_file += 'c'
with salt.utils.files.fopen(shim_file) as ssh_py_shim:
SSH_PY_SHIM = ssh_py_shim.read()
log = logging.getLogger(__name__)
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
def lowstate_file_refs(chunks):
'''
Create a list of file ref objects to reconcile
'''
refs = {}
for chunk in chunks:
saltenv = 'base'
crefs = []
for state in chunk:
if state == '__env__':
saltenv = chunk[state]
elif state == 'saltenv':
saltenv = chunk[state]
elif state.startswith('__'):
continue
crefs.extend(salt_refs(chunk[state]))
if crefs:
if saltenv not in refs:
refs[saltenv] = []
refs[saltenv].append(crefs)
return refs
def mod_data(fsclient):
'''
Generate the module arguments for the shim data
'''
# TODO, change out for a fileserver backend
sync_refs = [
'modules',
'states',
'grains',
'renderers',
'returners',
]
ret = {}
envs = fsclient.envs()
ver_base = ''
for env in envs:
files = fsclient.file_list(env)
for ref in sync_refs:
mods_data = {}
pref = '_{0}'.format(ref)
for fn_ in sorted(files):
if fn_.startswith(pref):
if fn_.endswith(('.py', '.so', '.pyx')):
full = salt.utils.url.create(fn_)
mod_path = fsclient.cache_file(full, env)
if not os.path.isfile(mod_path):
continue
mods_data[os.path.basename(fn_)] = mod_path
chunk = salt.utils.hashutils.get_hash(mod_path)
ver_base += chunk
if mods_data:
if ref in ret:
ret[ref].update(mods_data)
else:
ret[ref] = mods_data
if not ret:
return {}
if six.PY3:
ver_base = salt.utils.stringutils.to_bytes(ver_base)
ver = hashlib.sha1(ver_base).hexdigest()
ext_tar_path = os.path.join(
fsclient.opts['cachedir'],
'ext_mods.{0}.tgz'.format(ver))
mods = {'version': ver,
'file': ext_tar_path}
if os.path.isfile(ext_tar_path):
return mods
tfp = tarfile.open(ext_tar_path, 'w:gz')
verfile = os.path.join(fsclient.opts['cachedir'], 'ext_mods.ver')
with salt.utils.files.fopen(verfile, 'w+') as fp_:
fp_.write(ver)
tfp.add(verfile, 'ext_version')
for ref in ret:
for fn_ in ret[ref]:
tfp.add(ret[ref][fn_], os.path.join(ref, fn_))
tfp.close()
return mods
def ssh_version():
'''
Returns the version of the installed ssh command
'''
# This function needs more granular checks and to be validated against
# older versions of ssh
ret = subprocess.Popen(
['ssh', '-V'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
try:
version_parts = ret[1].split(b',')[0].split(b'_')[1]
parts = []
for part in version_parts:
try:
parts.append(int(part))
except ValueError:
return tuple(parts)
return tuple(parts)
except IndexError:
return (2, 0)
def _convert_args(args):
'''
Take a list of args, and convert any dicts inside the list to keyword
args in the form of `key=value`, ready to be passed to salt-ssh
'''
converted = []
for arg in args:
if isinstance(arg, dict):
for key in list(arg.keys()):
if key == '__kwarg__':
continue
converted.append('{0}={1}'.format(key, arg[key]))
else:
converted.append(arg)
return converted
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
mod_data
|
python
|
def mod_data(fsclient):
'''
Generate the module arguments for the shim data
'''
# TODO, change out for a fileserver backend
sync_refs = [
'modules',
'states',
'grains',
'renderers',
'returners',
]
ret = {}
envs = fsclient.envs()
ver_base = ''
for env in envs:
files = fsclient.file_list(env)
for ref in sync_refs:
mods_data = {}
pref = '_{0}'.format(ref)
for fn_ in sorted(files):
if fn_.startswith(pref):
if fn_.endswith(('.py', '.so', '.pyx')):
full = salt.utils.url.create(fn_)
mod_path = fsclient.cache_file(full, env)
if not os.path.isfile(mod_path):
continue
mods_data[os.path.basename(fn_)] = mod_path
chunk = salt.utils.hashutils.get_hash(mod_path)
ver_base += chunk
if mods_data:
if ref in ret:
ret[ref].update(mods_data)
else:
ret[ref] = mods_data
if not ret:
return {}
if six.PY3:
ver_base = salt.utils.stringutils.to_bytes(ver_base)
ver = hashlib.sha1(ver_base).hexdigest()
ext_tar_path = os.path.join(
fsclient.opts['cachedir'],
'ext_mods.{0}.tgz'.format(ver))
mods = {'version': ver,
'file': ext_tar_path}
if os.path.isfile(ext_tar_path):
return mods
tfp = tarfile.open(ext_tar_path, 'w:gz')
verfile = os.path.join(fsclient.opts['cachedir'], 'ext_mods.ver')
with salt.utils.files.fopen(verfile, 'w+') as fp_:
fp_.write(ver)
tfp.add(verfile, 'ext_version')
for ref in ret:
for fn_ in ret[ref]:
tfp.add(ret[ref][fn_], os.path.join(ref, fn_))
tfp.close()
return mods
|
Generate the module arguments for the shim data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L1575-L1633
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
# -*- coding: utf-8 -*-
'''
Create ssh executor system
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import copy
import getpass
import logging
import multiprocessing
import subprocess
import hashlib
import tarfile
import os
import re
import sys
import time
import uuid
import tempfile
import binascii
import sys
import datetime
# Import salt libs
import salt.output
import salt.client.ssh.shell
import salt.client.ssh.wrapper
import salt.config
import salt.exceptions
import salt.defaults.exitcodes
import salt.log
import salt.loader
import salt.minion
import salt.roster
import salt.serializers.yaml
import salt.state
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.json
import salt.utils.network
import salt.utils.path
import salt.utils.stringutils
import salt.utils.thin
import salt.utils.url
import salt.utils.verify
from salt.utils.platform import is_windows
from salt.utils.process import MultiprocessingProcess
import salt.roster
from salt.template import compile_template
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin
try:
import saltwinshell
HAS_WINSHELL = True
except ImportError:
HAS_WINSHELL = False
from salt.utils.zeromq import zmq
# The directory where salt thin is deployed
DEFAULT_THIN_DIR = '/var/tmp/.%%USER%%_%%FQDNUUID%%_salt'
# RSTR is just a delimiter to distinguish the beginning of salt STDOUT
# and STDERR. There is no special meaning. Messages prior to RSTR in
# stderr and stdout are either from SSH or from the shim.
#
# RSTR on both stdout and stderr:
# no errors in SHIM - output after RSTR is from salt
# No RSTR in stderr, RSTR in stdout:
# no errors in SSH_SH_SHIM, but SHIM commands for salt master are after
# RSTR in stdout
# No RSTR in stderr, no RSTR in stdout:
# Failure in SHIM
# RSTR in stderr, No RSTR in stdout:
# Undefined behavior
RSTR = '_edbc7885e4f9aac9b83b35999b68d015148caf467b78fa39c05f669c0ff89878'
# The regex to find RSTR in output - Must be on an output line by itself
# NOTE - must use non-grouping match groups or output splitting will fail.
RSTR_RE = r'(?:^|\r?\n)' + RSTR + r'(?:\r?\n|$)'
# METHODOLOGY:
#
# 1) Make the _thinnest_ /bin/sh shim (SSH_SH_SHIM) to find the python
# interpreter and get it invoked
# 2) Once a qualified python is found start it with the SSH_PY_SHIM
# 3) The shim is converted to a single semicolon separated line, so
# some constructs are needed to keep it clean.
# NOTE:
# * SSH_SH_SHIM is generic and can be used to load+exec *any* python
# script on the target.
# * SSH_PY_SHIM is in a separate file rather than stuffed in a string
# in salt/client/ssh/__init__.py - this makes testing *easy* because
# it can be invoked directly.
# * SSH_PY_SHIM is base64 encoded and formatted into the SSH_SH_SHIM
# string. This makes the python script "armored" so that it can
# all be passed in the SSH command and will not need special quoting
# (which likely would be impossibe to do anyway)
# * The formatted SSH_SH_SHIM with the SSH_PY_SHIM payload is a bit
# big (~7.5k). If this proves problematic for an SSH command we
# might try simply invoking "/bin/sh -s" and passing the formatted
# SSH_SH_SHIM on SSH stdin.
# NOTE: there are two passes of formatting:
# 1) Substitute in static values
# - EX_THIN_PYTHON_INVALID - exit code if a suitable python is not found
# 2) Substitute in instance-specific commands
# - DEBUG - enable shim debugging (any non-zero string enables)
# - SUDO - load python and execute as root (any non-zero string enables)
# - SSH_PY_CODE - base64-encoded python code to execute
# - SSH_PY_ARGS - arguments to pass to python code
# This shim generically loads python code . . . and *no* more.
# - Uses /bin/sh for maximum compatibility - then jumps to
# python for ultra-maximum compatibility.
#
# 1. Identify a suitable python
# 2. Jump to python
# Note the list-comprehension syntax to define SSH_SH_SHIM is needed
# to be able to define the string with indentation for readability but
# still strip the white space for compactness and to avoid issues with
# some multi-line embedded python code having indentation errors
SSH_SH_SHIM = \
'\n'.join(
[s.strip() for s in r'''/bin/sh << 'EOF'
set -e
set -u
DEBUG="{{DEBUG}}"
if [ -n "$DEBUG" ]
then set -x
fi
SUDO=""
if [ -n "{{SUDO}}" ]
then SUDO="sudo "
fi
SUDO_USER="{{SUDO_USER}}"
if [ "$SUDO" ] && [ "$SUDO_USER" ]
then SUDO="sudo -u {{SUDO_USER}}"
elif [ "$SUDO" ] && [ -n "$SUDO_USER" ]
then SUDO="sudo "
fi
EX_PYTHON_INVALID={EX_THIN_PYTHON_INVALID}
PYTHON_CMDS="python3 python27 python2.7 python26 python2.6 python2 python"
for py_cmd in $PYTHON_CMDS
do
if command -v "$py_cmd" >/dev/null 2>&1 && "$py_cmd" -c "import sys; sys.exit(not (sys.version_info >= (2, 6)));"
then
py_cmd_path=`"$py_cmd" -c 'from __future__ import print_function;import sys; print(sys.executable);'`
cmdpath=`command -v $py_cmd 2>/dev/null || which $py_cmd 2>/dev/null`
if file $cmdpath | grep "shell script" > /dev/null
then
ex_vars="'PATH', 'LD_LIBRARY_PATH', 'MANPATH', \
'XDG_DATA_DIRS', 'PKG_CONFIG_PATH'"
export `$py_cmd -c \
"from __future__ import print_function;
import sys;
import os;
map(sys.stdout.write, ['{{{{0}}}}={{{{1}}}} ' \
.format(x, os.environ[x]) for x in [$ex_vars]])"`
exec $SUDO PATH=$PATH LD_LIBRARY_PATH=$LD_LIBRARY_PATH \
MANPATH=$MANPATH XDG_DATA_DIRS=$XDG_DATA_DIRS \
PKG_CONFIG_PATH=$PKG_CONFIG_PATH \
"$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
else
exec $SUDO "$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
fi
exit 0
else
continue
fi
done
echo "ERROR: Unable to locate appropriate python command" >&2
exit $EX_PYTHON_INVALID
EOF'''.format(
EX_THIN_PYTHON_INVALID=salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,
).split('\n')])
if not is_windows():
shim_file = os.path.join(os.path.dirname(__file__), 'ssh_py_shim.py')
if not os.path.exists(shim_file):
# On esky builds we only have the .pyc file
shim_file += 'c'
with salt.utils.files.fopen(shim_file) as ssh_py_shim:
SSH_PY_SHIM = ssh_py_shim.read()
log = logging.getLogger(__name__)
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
def lowstate_file_refs(chunks):
'''
Create a list of file ref objects to reconcile
'''
refs = {}
for chunk in chunks:
saltenv = 'base'
crefs = []
for state in chunk:
if state == '__env__':
saltenv = chunk[state]
elif state == 'saltenv':
saltenv = chunk[state]
elif state.startswith('__'):
continue
crefs.extend(salt_refs(chunk[state]))
if crefs:
if saltenv not in refs:
refs[saltenv] = []
refs[saltenv].append(crefs)
return refs
def salt_refs(data):
'''
Pull salt file references out of the states
'''
proto = 'salt://'
ret = []
if isinstance(data, six.string_types):
if data.startswith(proto):
return [data]
if isinstance(data, list):
for comp in data:
if isinstance(comp, six.string_types):
if comp.startswith(proto):
ret.append(comp)
return ret
def ssh_version():
'''
Returns the version of the installed ssh command
'''
# This function needs more granular checks and to be validated against
# older versions of ssh
ret = subprocess.Popen(
['ssh', '-V'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
try:
version_parts = ret[1].split(b',')[0].split(b'_')[1]
parts = []
for part in version_parts:
try:
parts.append(int(part))
except ValueError:
return tuple(parts)
return tuple(parts)
except IndexError:
return (2, 0)
def _convert_args(args):
'''
Take a list of args, and convert any dicts inside the list to keyword
args in the form of `key=value`, ready to be passed to salt-ssh
'''
converted = []
for arg in args:
if isinstance(arg, dict):
for key in list(arg.keys()):
if key == '__kwarg__':
continue
converted.append('{0}={1}'.format(key, arg[key]))
else:
converted.append(arg)
return converted
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
ssh_version
|
python
|
def ssh_version():
'''
Returns the version of the installed ssh command
'''
# This function needs more granular checks and to be validated against
# older versions of ssh
ret = subprocess.Popen(
['ssh', '-V'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
try:
version_parts = ret[1].split(b',')[0].split(b'_')[1]
parts = []
for part in version_parts:
try:
parts.append(int(part))
except ValueError:
return tuple(parts)
return tuple(parts)
except IndexError:
return (2, 0)
|
Returns the version of the installed ssh command
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L1636-L1656
| null |
# -*- coding: utf-8 -*-
'''
Create ssh executor system
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import copy
import getpass
import logging
import multiprocessing
import subprocess
import hashlib
import tarfile
import os
import re
import sys
import time
import uuid
import tempfile
import binascii
import sys
import datetime
# Import salt libs
import salt.output
import salt.client.ssh.shell
import salt.client.ssh.wrapper
import salt.config
import salt.exceptions
import salt.defaults.exitcodes
import salt.log
import salt.loader
import salt.minion
import salt.roster
import salt.serializers.yaml
import salt.state
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.json
import salt.utils.network
import salt.utils.path
import salt.utils.stringutils
import salt.utils.thin
import salt.utils.url
import salt.utils.verify
from salt.utils.platform import is_windows
from salt.utils.process import MultiprocessingProcess
import salt.roster
from salt.template import compile_template
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin
try:
import saltwinshell
HAS_WINSHELL = True
except ImportError:
HAS_WINSHELL = False
from salt.utils.zeromq import zmq
# The directory where salt thin is deployed
DEFAULT_THIN_DIR = '/var/tmp/.%%USER%%_%%FQDNUUID%%_salt'
# RSTR is just a delimiter to distinguish the beginning of salt STDOUT
# and STDERR. There is no special meaning. Messages prior to RSTR in
# stderr and stdout are either from SSH or from the shim.
#
# RSTR on both stdout and stderr:
# no errors in SHIM - output after RSTR is from salt
# No RSTR in stderr, RSTR in stdout:
# no errors in SSH_SH_SHIM, but SHIM commands for salt master are after
# RSTR in stdout
# No RSTR in stderr, no RSTR in stdout:
# Failure in SHIM
# RSTR in stderr, No RSTR in stdout:
# Undefined behavior
RSTR = '_edbc7885e4f9aac9b83b35999b68d015148caf467b78fa39c05f669c0ff89878'
# The regex to find RSTR in output - Must be on an output line by itself
# NOTE - must use non-grouping match groups or output splitting will fail.
RSTR_RE = r'(?:^|\r?\n)' + RSTR + r'(?:\r?\n|$)'
# METHODOLOGY:
#
# 1) Make the _thinnest_ /bin/sh shim (SSH_SH_SHIM) to find the python
# interpreter and get it invoked
# 2) Once a qualified python is found start it with the SSH_PY_SHIM
# 3) The shim is converted to a single semicolon separated line, so
# some constructs are needed to keep it clean.
# NOTE:
# * SSH_SH_SHIM is generic and can be used to load+exec *any* python
# script on the target.
# * SSH_PY_SHIM is in a separate file rather than stuffed in a string
# in salt/client/ssh/__init__.py - this makes testing *easy* because
# it can be invoked directly.
# * SSH_PY_SHIM is base64 encoded and formatted into the SSH_SH_SHIM
# string. This makes the python script "armored" so that it can
# all be passed in the SSH command and will not need special quoting
# (which likely would be impossibe to do anyway)
# * The formatted SSH_SH_SHIM with the SSH_PY_SHIM payload is a bit
# big (~7.5k). If this proves problematic for an SSH command we
# might try simply invoking "/bin/sh -s" and passing the formatted
# SSH_SH_SHIM on SSH stdin.
# NOTE: there are two passes of formatting:
# 1) Substitute in static values
# - EX_THIN_PYTHON_INVALID - exit code if a suitable python is not found
# 2) Substitute in instance-specific commands
# - DEBUG - enable shim debugging (any non-zero string enables)
# - SUDO - load python and execute as root (any non-zero string enables)
# - SSH_PY_CODE - base64-encoded python code to execute
# - SSH_PY_ARGS - arguments to pass to python code
# This shim generically loads python code . . . and *no* more.
# - Uses /bin/sh for maximum compatibility - then jumps to
# python for ultra-maximum compatibility.
#
# 1. Identify a suitable python
# 2. Jump to python
# Note the list-comprehension syntax to define SSH_SH_SHIM is needed
# to be able to define the string with indentation for readability but
# still strip the white space for compactness and to avoid issues with
# some multi-line embedded python code having indentation errors
SSH_SH_SHIM = \
'\n'.join(
[s.strip() for s in r'''/bin/sh << 'EOF'
set -e
set -u
DEBUG="{{DEBUG}}"
if [ -n "$DEBUG" ]
then set -x
fi
SUDO=""
if [ -n "{{SUDO}}" ]
then SUDO="sudo "
fi
SUDO_USER="{{SUDO_USER}}"
if [ "$SUDO" ] && [ "$SUDO_USER" ]
then SUDO="sudo -u {{SUDO_USER}}"
elif [ "$SUDO" ] && [ -n "$SUDO_USER" ]
then SUDO="sudo "
fi
EX_PYTHON_INVALID={EX_THIN_PYTHON_INVALID}
PYTHON_CMDS="python3 python27 python2.7 python26 python2.6 python2 python"
for py_cmd in $PYTHON_CMDS
do
if command -v "$py_cmd" >/dev/null 2>&1 && "$py_cmd" -c "import sys; sys.exit(not (sys.version_info >= (2, 6)));"
then
py_cmd_path=`"$py_cmd" -c 'from __future__ import print_function;import sys; print(sys.executable);'`
cmdpath=`command -v $py_cmd 2>/dev/null || which $py_cmd 2>/dev/null`
if file $cmdpath | grep "shell script" > /dev/null
then
ex_vars="'PATH', 'LD_LIBRARY_PATH', 'MANPATH', \
'XDG_DATA_DIRS', 'PKG_CONFIG_PATH'"
export `$py_cmd -c \
"from __future__ import print_function;
import sys;
import os;
map(sys.stdout.write, ['{{{{0}}}}={{{{1}}}} ' \
.format(x, os.environ[x]) for x in [$ex_vars]])"`
exec $SUDO PATH=$PATH LD_LIBRARY_PATH=$LD_LIBRARY_PATH \
MANPATH=$MANPATH XDG_DATA_DIRS=$XDG_DATA_DIRS \
PKG_CONFIG_PATH=$PKG_CONFIG_PATH \
"$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
else
exec $SUDO "$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
fi
exit 0
else
continue
fi
done
echo "ERROR: Unable to locate appropriate python command" >&2
exit $EX_PYTHON_INVALID
EOF'''.format(
EX_THIN_PYTHON_INVALID=salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,
).split('\n')])
if not is_windows():
shim_file = os.path.join(os.path.dirname(__file__), 'ssh_py_shim.py')
if not os.path.exists(shim_file):
# On esky builds we only have the .pyc file
shim_file += 'c'
with salt.utils.files.fopen(shim_file) as ssh_py_shim:
SSH_PY_SHIM = ssh_py_shim.read()
log = logging.getLogger(__name__)
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
def lowstate_file_refs(chunks):
'''
Create a list of file ref objects to reconcile
'''
refs = {}
for chunk in chunks:
saltenv = 'base'
crefs = []
for state in chunk:
if state == '__env__':
saltenv = chunk[state]
elif state == 'saltenv':
saltenv = chunk[state]
elif state.startswith('__'):
continue
crefs.extend(salt_refs(chunk[state]))
if crefs:
if saltenv not in refs:
refs[saltenv] = []
refs[saltenv].append(crefs)
return refs
def salt_refs(data):
'''
Pull salt file references out of the states
'''
proto = 'salt://'
ret = []
if isinstance(data, six.string_types):
if data.startswith(proto):
return [data]
if isinstance(data, list):
for comp in data:
if isinstance(comp, six.string_types):
if comp.startswith(proto):
ret.append(comp)
return ret
def mod_data(fsclient):
'''
Generate the module arguments for the shim data
'''
# TODO, change out for a fileserver backend
sync_refs = [
'modules',
'states',
'grains',
'renderers',
'returners',
]
ret = {}
envs = fsclient.envs()
ver_base = ''
for env in envs:
files = fsclient.file_list(env)
for ref in sync_refs:
mods_data = {}
pref = '_{0}'.format(ref)
for fn_ in sorted(files):
if fn_.startswith(pref):
if fn_.endswith(('.py', '.so', '.pyx')):
full = salt.utils.url.create(fn_)
mod_path = fsclient.cache_file(full, env)
if not os.path.isfile(mod_path):
continue
mods_data[os.path.basename(fn_)] = mod_path
chunk = salt.utils.hashutils.get_hash(mod_path)
ver_base += chunk
if mods_data:
if ref in ret:
ret[ref].update(mods_data)
else:
ret[ref] = mods_data
if not ret:
return {}
if six.PY3:
ver_base = salt.utils.stringutils.to_bytes(ver_base)
ver = hashlib.sha1(ver_base).hexdigest()
ext_tar_path = os.path.join(
fsclient.opts['cachedir'],
'ext_mods.{0}.tgz'.format(ver))
mods = {'version': ver,
'file': ext_tar_path}
if os.path.isfile(ext_tar_path):
return mods
tfp = tarfile.open(ext_tar_path, 'w:gz')
verfile = os.path.join(fsclient.opts['cachedir'], 'ext_mods.ver')
with salt.utils.files.fopen(verfile, 'w+') as fp_:
fp_.write(ver)
tfp.add(verfile, 'ext_version')
for ref in ret:
for fn_ in ret[ref]:
tfp.add(ret[ref][fn_], os.path.join(ref, fn_))
tfp.close()
return mods
def _convert_args(args):
'''
Take a list of args, and convert any dicts inside the list to keyword
args in the form of `key=value`, ready to be passed to salt-ssh
'''
converted = []
for arg in args:
if isinstance(arg, dict):
for key in list(arg.keys()):
if key == '__kwarg__':
continue
converted.append('{0}={1}'.format(key, arg[key]))
else:
converted.append(arg)
return converted
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
_convert_args
|
python
|
def _convert_args(args):
'''
Take a list of args, and convert any dicts inside the list to keyword
args in the form of `key=value`, ready to be passed to salt-ssh
'''
converted = []
for arg in args:
if isinstance(arg, dict):
for key in list(arg.keys()):
if key == '__kwarg__':
continue
converted.append('{0}={1}'.format(key, arg[key]))
else:
converted.append(arg)
return converted
|
Take a list of args, and convert any dicts inside the list to keyword
args in the form of `key=value`, ready to be passed to salt-ssh
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L1659-L1673
| null |
# -*- coding: utf-8 -*-
'''
Create ssh executor system
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import base64
import copy
import getpass
import logging
import multiprocessing
import subprocess
import hashlib
import tarfile
import os
import re
import sys
import time
import uuid
import tempfile
import binascii
import sys
import datetime
# Import salt libs
import salt.output
import salt.client.ssh.shell
import salt.client.ssh.wrapper
import salt.config
import salt.exceptions
import salt.defaults.exitcodes
import salt.log
import salt.loader
import salt.minion
import salt.roster
import salt.serializers.yaml
import salt.state
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.json
import salt.utils.network
import salt.utils.path
import salt.utils.stringutils
import salt.utils.thin
import salt.utils.url
import salt.utils.verify
from salt.utils.platform import is_windows
from salt.utils.process import MultiprocessingProcess
import salt.roster
from salt.template import compile_template
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin
try:
import saltwinshell
HAS_WINSHELL = True
except ImportError:
HAS_WINSHELL = False
from salt.utils.zeromq import zmq
# The directory where salt thin is deployed
DEFAULT_THIN_DIR = '/var/tmp/.%%USER%%_%%FQDNUUID%%_salt'
# RSTR is just a delimiter to distinguish the beginning of salt STDOUT
# and STDERR. There is no special meaning. Messages prior to RSTR in
# stderr and stdout are either from SSH or from the shim.
#
# RSTR on both stdout and stderr:
# no errors in SHIM - output after RSTR is from salt
# No RSTR in stderr, RSTR in stdout:
# no errors in SSH_SH_SHIM, but SHIM commands for salt master are after
# RSTR in stdout
# No RSTR in stderr, no RSTR in stdout:
# Failure in SHIM
# RSTR in stderr, No RSTR in stdout:
# Undefined behavior
RSTR = '_edbc7885e4f9aac9b83b35999b68d015148caf467b78fa39c05f669c0ff89878'
# The regex to find RSTR in output - Must be on an output line by itself
# NOTE - must use non-grouping match groups or output splitting will fail.
RSTR_RE = r'(?:^|\r?\n)' + RSTR + r'(?:\r?\n|$)'
# METHODOLOGY:
#
# 1) Make the _thinnest_ /bin/sh shim (SSH_SH_SHIM) to find the python
# interpreter and get it invoked
# 2) Once a qualified python is found start it with the SSH_PY_SHIM
# 3) The shim is converted to a single semicolon separated line, so
# some constructs are needed to keep it clean.
# NOTE:
# * SSH_SH_SHIM is generic and can be used to load+exec *any* python
# script on the target.
# * SSH_PY_SHIM is in a separate file rather than stuffed in a string
# in salt/client/ssh/__init__.py - this makes testing *easy* because
# it can be invoked directly.
# * SSH_PY_SHIM is base64 encoded and formatted into the SSH_SH_SHIM
# string. This makes the python script "armored" so that it can
# all be passed in the SSH command and will not need special quoting
# (which likely would be impossibe to do anyway)
# * The formatted SSH_SH_SHIM with the SSH_PY_SHIM payload is a bit
# big (~7.5k). If this proves problematic for an SSH command we
# might try simply invoking "/bin/sh -s" and passing the formatted
# SSH_SH_SHIM on SSH stdin.
# NOTE: there are two passes of formatting:
# 1) Substitute in static values
# - EX_THIN_PYTHON_INVALID - exit code if a suitable python is not found
# 2) Substitute in instance-specific commands
# - DEBUG - enable shim debugging (any non-zero string enables)
# - SUDO - load python and execute as root (any non-zero string enables)
# - SSH_PY_CODE - base64-encoded python code to execute
# - SSH_PY_ARGS - arguments to pass to python code
# This shim generically loads python code . . . and *no* more.
# - Uses /bin/sh for maximum compatibility - then jumps to
# python for ultra-maximum compatibility.
#
# 1. Identify a suitable python
# 2. Jump to python
# Note the list-comprehension syntax to define SSH_SH_SHIM is needed
# to be able to define the string with indentation for readability but
# still strip the white space for compactness and to avoid issues with
# some multi-line embedded python code having indentation errors
SSH_SH_SHIM = \
'\n'.join(
[s.strip() for s in r'''/bin/sh << 'EOF'
set -e
set -u
DEBUG="{{DEBUG}}"
if [ -n "$DEBUG" ]
then set -x
fi
SUDO=""
if [ -n "{{SUDO}}" ]
then SUDO="sudo "
fi
SUDO_USER="{{SUDO_USER}}"
if [ "$SUDO" ] && [ "$SUDO_USER" ]
then SUDO="sudo -u {{SUDO_USER}}"
elif [ "$SUDO" ] && [ -n "$SUDO_USER" ]
then SUDO="sudo "
fi
EX_PYTHON_INVALID={EX_THIN_PYTHON_INVALID}
PYTHON_CMDS="python3 python27 python2.7 python26 python2.6 python2 python"
for py_cmd in $PYTHON_CMDS
do
if command -v "$py_cmd" >/dev/null 2>&1 && "$py_cmd" -c "import sys; sys.exit(not (sys.version_info >= (2, 6)));"
then
py_cmd_path=`"$py_cmd" -c 'from __future__ import print_function;import sys; print(sys.executable);'`
cmdpath=`command -v $py_cmd 2>/dev/null || which $py_cmd 2>/dev/null`
if file $cmdpath | grep "shell script" > /dev/null
then
ex_vars="'PATH', 'LD_LIBRARY_PATH', 'MANPATH', \
'XDG_DATA_DIRS', 'PKG_CONFIG_PATH'"
export `$py_cmd -c \
"from __future__ import print_function;
import sys;
import os;
map(sys.stdout.write, ['{{{{0}}}}={{{{1}}}} ' \
.format(x, os.environ[x]) for x in [$ex_vars]])"`
exec $SUDO PATH=$PATH LD_LIBRARY_PATH=$LD_LIBRARY_PATH \
MANPATH=$MANPATH XDG_DATA_DIRS=$XDG_DATA_DIRS \
PKG_CONFIG_PATH=$PKG_CONFIG_PATH \
"$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
else
exec $SUDO "$py_cmd_path" -c \
'import base64;
exec(base64.b64decode("""{{SSH_PY_CODE}}""").decode("utf-8"))'
fi
exit 0
else
continue
fi
done
echo "ERROR: Unable to locate appropriate python command" >&2
exit $EX_PYTHON_INVALID
EOF'''.format(
EX_THIN_PYTHON_INVALID=salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,
).split('\n')])
if not is_windows():
shim_file = os.path.join(os.path.dirname(__file__), 'ssh_py_shim.py')
if not os.path.exists(shim_file):
# On esky builds we only have the .pyc file
shim_file += 'c'
with salt.utils.files.fopen(shim_file) as ssh_py_shim:
SSH_PY_SHIM = ssh_py_shim.read()
log = logging.getLogger(__name__)
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
def lowstate_file_refs(chunks):
'''
Create a list of file ref objects to reconcile
'''
refs = {}
for chunk in chunks:
saltenv = 'base'
crefs = []
for state in chunk:
if state == '__env__':
saltenv = chunk[state]
elif state == 'saltenv':
saltenv = chunk[state]
elif state.startswith('__'):
continue
crefs.extend(salt_refs(chunk[state]))
if crefs:
if saltenv not in refs:
refs[saltenv] = []
refs[saltenv].append(crefs)
return refs
def salt_refs(data):
'''
Pull salt file references out of the states
'''
proto = 'salt://'
ret = []
if isinstance(data, six.string_types):
if data.startswith(proto):
return [data]
if isinstance(data, list):
for comp in data:
if isinstance(comp, six.string_types):
if comp.startswith(proto):
ret.append(comp)
return ret
def mod_data(fsclient):
'''
Generate the module arguments for the shim data
'''
# TODO, change out for a fileserver backend
sync_refs = [
'modules',
'states',
'grains',
'renderers',
'returners',
]
ret = {}
envs = fsclient.envs()
ver_base = ''
for env in envs:
files = fsclient.file_list(env)
for ref in sync_refs:
mods_data = {}
pref = '_{0}'.format(ref)
for fn_ in sorted(files):
if fn_.startswith(pref):
if fn_.endswith(('.py', '.so', '.pyx')):
full = salt.utils.url.create(fn_)
mod_path = fsclient.cache_file(full, env)
if not os.path.isfile(mod_path):
continue
mods_data[os.path.basename(fn_)] = mod_path
chunk = salt.utils.hashutils.get_hash(mod_path)
ver_base += chunk
if mods_data:
if ref in ret:
ret[ref].update(mods_data)
else:
ret[ref] = mods_data
if not ret:
return {}
if six.PY3:
ver_base = salt.utils.stringutils.to_bytes(ver_base)
ver = hashlib.sha1(ver_base).hexdigest()
ext_tar_path = os.path.join(
fsclient.opts['cachedir'],
'ext_mods.{0}.tgz'.format(ver))
mods = {'version': ver,
'file': ext_tar_path}
if os.path.isfile(ext_tar_path):
return mods
tfp = tarfile.open(ext_tar_path, 'w:gz')
verfile = os.path.join(fsclient.opts['cachedir'], 'ext_mods.ver')
with salt.utils.files.fopen(verfile, 'w+') as fp_:
fp_.write(ver)
tfp.add(verfile, 'ext_version')
for ref in ret:
for fn_ in ret[ref]:
tfp.add(ret[ref][fn_], os.path.join(ref, fn_))
tfp.close()
return mods
def ssh_version():
'''
Returns the version of the installed ssh command
'''
# This function needs more granular checks and to be validated against
# older versions of ssh
ret = subprocess.Popen(
['ssh', '-V'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
try:
version_parts = ret[1].split(b',')[0].split(b'_')[1]
parts = []
for part in version_parts:
try:
parts.append(int(part))
except ValueError:
return tuple(parts)
return tuple(parts)
except IndexError:
return (2, 0)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH._get_roster
|
python
|
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
|
Read roster filename as a key to the data.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L330-L341
| null |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH._expand_target
|
python
|
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
|
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L343-L371
|
[
"def is_reachable_host(entity_name):\n '''\n Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc).\n :param hostname:\n :return:\n '''\n try:\n assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list\n ret = True\n except socket.gaierror:\n ret = False\n\n return ret\n"
] |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH._update_roster
|
python
|
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
|
Update default flat roster with the passed in information.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L373-L392
| null |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH._update_targets
|
python
|
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
|
Uptade targets in case hostname was directly passed without the roster.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L394-L417
|
[
"def is_reachable_host(entity_name):\n '''\n Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc).\n :param hostname:\n :return:\n '''\n try:\n assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list\n ret = True\n except socket.gaierror:\n ret = False\n\n return ret\n"
] |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH.get_pubkey
|
python
|
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
|
Return the key string for the SSH public key
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L419-L438
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH.key_deploy
|
python
|
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
|
Deploy the SSH key if the minions don't auth
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L440-L461
|
[
"def _key_deploy_run(self, host, target, re_run=True):\n '''\n The ssh-copy-id routine\n '''\n argv = [\n 'ssh.set_auth_key',\n target.get('user', 'root'),\n self.get_pubkey(),\n ]\n\n single = Single(\n self.opts,\n argv,\n host,\n mods=self.mods,\n fsclient=self.fsclient,\n thin=self.thin,\n **target)\n if salt.utils.path.which('ssh-copy-id'):\n # we have ssh-copy-id, use it!\n stdout, stderr, retcode = single.shell.copy_id()\n else:\n stdout, stderr, retcode = single.run()\n if re_run:\n target.pop('passwd')\n single = Single(\n self.opts,\n self.opts['argv'],\n host,\n mods=self.mods,\n fsclient=self.fsclient,\n thin=self.thin,\n **target)\n stdout, stderr, retcode = single.cmd_block()\n try:\n data = salt.utils.json.find_json(stdout)\n return {host: data.get('local', data)}\n except Exception:\n if stderr:\n return {host: stderr}\n return {host: 'Bad Return'}\n if salt.defaults.exitcodes.EX_OK != retcode:\n return {host: stderr}\n return {host: stdout}\n"
] |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH._key_deploy_run
|
python
|
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
|
The ssh-copy-id routine
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L463-L506
|
[
"def find_json(raw):\n '''\n Pass in a raw string and load the json when it starts. This allows for a\n string to start with garbage and end with json but be cleanly loaded\n '''\n ret = {}\n lines = __split(raw)\n for ind, _ in enumerate(lines):\n try:\n working = '\\n'.join(lines[ind:])\n except UnicodeDecodeError:\n working = '\\n'.join(salt.utils.data.decode(lines[ind:]))\n\n try:\n ret = json.loads(working) # future lint: blacklisted-function\n except ValueError:\n continue\n if ret:\n return ret\n if not ret:\n # Not json, raise an error\n raise ValueError\n",
"def get_pubkey(self):\n '''\n Return the key string for the SSH public key\n '''\n if '__master_opts__' in self.opts and \\\n self.opts['__master_opts__'].get('ssh_use_home_key') and \\\n os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):\n priv = os.path.expanduser('~/.ssh/id_rsa')\n else:\n priv = self.opts.get(\n 'ssh_priv',\n os.path.join(\n self.opts['pki_dir'],\n 'ssh',\n 'salt-ssh.rsa'\n )\n )\n pub = '{0}.pub'.format(priv)\n with salt.utils.files.fopen(pub, 'r') as fp_:\n return '{0} rsa root@master'.format(fp_.read().split()[1])\n",
"def run(self, deploy_attempted=False):\n '''\n Execute the routine, the routine can be either:\n 1. Execute a raw shell command\n 2. Execute a wrapper func\n 3. Execute a remote Salt command\n\n If a (re)deploy is needed, then retry the operation after a deploy\n attempt\n\n Returns tuple of (stdout, stderr, retcode)\n '''\n stdout = stderr = retcode = None\n\n if self.opts.get('raw_shell', False):\n cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])\n stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)\n\n elif self.fun in self.wfuncs or self.mine:\n stdout, retcode = self.run_wfunc()\n\n else:\n stdout, stderr, retcode = self.cmd_block()\n\n return stdout, stderr, retcode\n",
"def cmd_block(self, is_retry=False):\n '''\n Prepare the pre-check command to send to the subsystem\n\n 1. execute SHIM + command\n 2. check if SHIM returns a master request or if it completed\n 3. handle any master request\n 4. re-execute SHIM + command\n 5. split SHIM results from command results\n 6. return command results\n '''\n self.argv = _convert_args(self.argv)\n log.debug(\n 'Performing shimmed, blocking command as follows:\\n%s',\n ' '.join([six.text_type(arg) for arg in self.argv])\n )\n cmd_str = self._cmd_str()\n stdout, stderr, retcode = self.shim_cmd(cmd_str)\n\n log.trace('STDOUT %s\\n%s', self.target['host'], stdout)\n log.trace('STDERR %s\\n%s', self.target['host'], stderr)\n log.debug('RETCODE %s: %s', self.target['host'], retcode)\n\n error = self.categorize_shim_errors(stdout, stderr, retcode)\n if error:\n if error == 'Python environment not found on Windows system':\n saltwinshell.deploy_python(self)\n stdout, stderr, retcode = self.shim_cmd(cmd_str)\n while re.search(RSTR_RE, stdout):\n stdout = re.split(RSTR_RE, stdout, 1)[1].strip()\n while re.search(RSTR_RE, stderr):\n stderr = re.split(RSTR_RE, stderr, 1)[1].strip()\n elif error == 'Undefined SHIM state':\n self.deploy()\n stdout, stderr, retcode = self.shim_cmd(cmd_str)\n if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):\n # If RSTR is not seen in both stdout and stderr then there\n # was a thin deployment problem.\n return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode\n while re.search(RSTR_RE, stdout):\n stdout = re.split(RSTR_RE, stdout, 1)[1].strip()\n while re.search(RSTR_RE, stderr):\n stderr = re.split(RSTR_RE, stderr, 1)[1].strip()\n else:\n return 'ERROR: {0}'.format(error), stderr, retcode\n\n # FIXME: this discards output from ssh_shim if the shim succeeds. It should\n # always save the shim output regardless of shim success or failure.\n while re.search(RSTR_RE, stdout):\n stdout = re.split(RSTR_RE, stdout, 1)[1].strip()\n\n if re.search(RSTR_RE, stderr):\n # Found RSTR in stderr which means SHIM completed and only\n # and remaining output is only from salt.\n while re.search(RSTR_RE, stderr):\n stderr = re.split(RSTR_RE, stderr, 1)[1].strip()\n\n else:\n # RSTR was found in stdout but not stderr - which means there\n # is a SHIM command for the master.\n shim_command = re.split(r'\\r?\\n', stdout, 1)[0].strip()\n log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)\n if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:\n self.deploy()\n stdout, stderr, retcode = self.shim_cmd(cmd_str)\n if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):\n if not self.tty:\n # If RSTR is not seen in both stdout and stderr then there\n # was a thin deployment problem.\n log.error(\n 'ERROR: Failure deploying thin, retrying:\\n'\n 'STDOUT:\\n%s\\nSTDERR:\\n%s\\nRETCODE: %s',\n stdout, stderr, retcode\n )\n return self.cmd_block()\n elif not re.search(RSTR_RE, stdout):\n # If RSTR is not seen in stdout with tty, then there\n # was a thin deployment problem.\n log.error(\n 'ERROR: Failure deploying thin, retrying:\\n'\n 'STDOUT:\\n%s\\nSTDERR:\\n%s\\nRETCODE: %s',\n stdout, stderr, retcode\n )\n while re.search(RSTR_RE, stdout):\n stdout = re.split(RSTR_RE, stdout, 1)[1].strip()\n if self.tty:\n stderr = ''\n else:\n while re.search(RSTR_RE, stderr):\n stderr = re.split(RSTR_RE, stderr, 1)[1].strip()\n elif 'ext_mods' == shim_command:\n self.deploy_ext()\n stdout, stderr, retcode = self.shim_cmd(cmd_str)\n if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):\n # If RSTR is not seen in both stdout and stderr then there\n # was a thin deployment problem.\n return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode\n while re.search(RSTR_RE, stdout):\n stdout = re.split(RSTR_RE, stdout, 1)[1].strip()\n while re.search(RSTR_RE, stderr):\n stderr = re.split(RSTR_RE, stderr, 1)[1].strip()\n\n return stdout, stderr, retcode\n"
] |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH.handle_routine
|
python
|
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
|
Run the routine in a "Thread", put a dict on the queue
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L508-L541
|
[
"def find_json(raw):\n '''\n Pass in a raw string and load the json when it starts. This allows for a\n string to start with garbage and end with json but be cleanly loaded\n '''\n ret = {}\n lines = __split(raw)\n for ind, _ in enumerate(lines):\n try:\n working = '\\n'.join(lines[ind:])\n except UnicodeDecodeError:\n working = '\\n'.join(salt.utils.data.decode(lines[ind:]))\n\n try:\n ret = json.loads(working) # future lint: blacklisted-function\n except ValueError:\n continue\n if ret:\n return ret\n if not ret:\n # Not json, raise an error\n raise ValueError\n",
"def run(self, deploy_attempted=False):\n '''\n Execute the routine, the routine can be either:\n 1. Execute a raw shell command\n 2. Execute a wrapper func\n 3. Execute a remote Salt command\n\n If a (re)deploy is needed, then retry the operation after a deploy\n attempt\n\n Returns tuple of (stdout, stderr, retcode)\n '''\n stdout = stderr = retcode = None\n\n if self.opts.get('raw_shell', False):\n cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])\n stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)\n\n elif self.fun in self.wfuncs or self.mine:\n stdout, retcode = self.run_wfunc()\n\n else:\n stdout, stderr, retcode = self.cmd_block()\n\n return stdout, stderr, retcode\n"
] |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH.handle_ssh
|
python
|
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
|
Spin up the needed threads or processes and execute the subsequent
routines
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L543-L637
| null |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH.run_iter
|
python
|
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
|
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L639-L691
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def tagify(suffix='', prefix='', base=SALT):\n '''\n convenience function to build a namespaced event tag string\n from joining with the TABPART character the base, prefix and suffix\n\n If string prefix is a valid key in TAGS Then use the value of key prefix\n Else use prefix string\n\n If suffix is a list Then join all string elements of suffix individually\n Else use string suffix\n\n '''\n parts = [base, TAGS.get(prefix, prefix)]\n if hasattr(suffix, 'append'): # list so extend parts\n parts.extend(suffix)\n else: # string so append\n parts.append(suffix)\n\n for index, _ in enumerate(parts):\n try:\n parts[index] = salt.utils.stringutils.to_str(parts[index])\n except TypeError:\n parts[index] = str(parts[index])\n return TAGPARTER.join([part for part in parts if part])\n",
"def handle_ssh(self, mine=False):\n '''\n Spin up the needed threads or processes and execute the subsequent\n routines\n '''\n que = multiprocessing.Queue()\n running = {}\n target_iter = self.targets.__iter__()\n returned = set()\n rets = set()\n init = False\n while True:\n if not self.targets:\n log.error('No matching targets found in roster.')\n break\n if len(running) < self.opts.get('ssh_max_procs', 25) and not init:\n try:\n host = next(target_iter)\n except StopIteration:\n init = True\n continue\n for default in self.defaults:\n if default not in self.targets[host]:\n self.targets[host][default] = self.defaults[default]\n if 'host' not in self.targets[host]:\n self.targets[host]['host'] = host\n if self.targets[host].get('winrm') and not HAS_WINSHELL:\n returned.add(host)\n rets.add(host)\n log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'\n log.debug(log_msg)\n no_ret = {'fun_args': [],\n 'jid': None,\n 'return': log_msg,\n 'retcode': 1,\n 'fun': '',\n 'id': host}\n yield {host: no_ret}\n continue\n args = (\n que,\n self.opts,\n host,\n self.targets[host],\n mine,\n )\n routine = MultiprocessingProcess(\n target=self.handle_routine,\n args=args)\n routine.start()\n running[host] = {'thread': routine}\n continue\n ret = {}\n try:\n ret = que.get(False)\n if 'id' in ret:\n returned.add(ret['id'])\n yield {ret['id']: ret['ret']}\n except Exception:\n # This bare exception is here to catch spurious exceptions\n # thrown by que.get during healthy operation. Please do not\n # worry about this bare exception, it is entirely here to\n # control program flow.\n pass\n for host in running:\n if not running[host]['thread'].is_alive():\n if host not in returned:\n # Try to get any returns that came through since we\n # last checked\n try:\n while True:\n ret = que.get(False)\n if 'id' in ret:\n returned.add(ret['id'])\n yield {ret['id']: ret['ret']}\n except Exception:\n pass\n\n if host not in returned:\n error = ('Target \\'{0}\\' did not return any data, '\n 'probably due to an error.').format(host)\n ret = {'id': host,\n 'ret': error}\n log.error(error)\n yield {ret['id']: ret['ret']}\n running[host]['thread'].join()\n rets.add(host)\n for host in rets:\n if host in running:\n running.pop(host)\n if len(rets) >= len(self.targets):\n break\n # Sleep when limit or all threads started\n if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):\n time.sleep(0.1)\n",
"def cache_job(self, jid, id_, ret, fun):\n '''\n Cache the job information\n '''\n self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,\n 'id': id_,\n 'return': ret,\n 'fun': fun})\n"
] |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH.cache_job
|
python
|
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
|
Cache the job information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L693-L700
| null |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
SSH.run
|
python
|
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
continue
ret[roster_file] = {}
for host_id in self.__parsed_rosters[roster_file]:
hostname = self.__parsed_rosters[roster_file][host_id]['host']
ret[roster_file][host_id] = hostname
salt.output.display_output(ret, 'nested', self.opts)
sys.exit()
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
try:
if isinstance(jid, bytes):
jid = jid.decode('utf-8')
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
except Exception as exc:
log.exception(exc)
log.error(
'Could not save load with returner %s: %s',
self.opts['master_job_cache'], exc
)
if self.opts.get('verbose'):
msg = 'Executing job with jid {0}'.format(jid)
print(msg)
print('-' * len(msg) + '\n')
print('')
sret = {}
outputter = self.opts.get('output', 'nested')
final_exit = 0
for ret in self.handle_ssh():
host = next(six.iterkeys(ret))
if isinstance(ret[host], dict):
host_ret = ret[host].get('retcode', 0)
if host_ret != 0:
final_exit = 1
else:
# Error on host
final_exit = 1
self.cache_job(jid, host, ret[host], fun)
ret = self.key_deploy(host, ret)
if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
ret[host] = ret[host]['stderr']
if not isinstance(ret[host], dict):
p_data = {host: ret[host]}
elif 'return' not in ret[host]:
p_data = ret
else:
outputter = ret[host].get('out', self.opts.get('output', 'nested'))
p_data = {host: ret[host].get('return', {})}
if self.opts.get('static'):
sret.update(p_data)
else:
salt.output.display_output(
p_data,
outputter,
self.opts)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
if self.opts.get('static'):
salt.output.display_output(
sret,
outputter,
self.opts)
if final_exit:
sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
|
Execute the overall routine, print results via outputters
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L702-L812
|
[
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def display_output(data, out=None, opts=None, **kwargs):\n '''\n Print the passed data using the desired output\n '''\n if opts is None:\n opts = {}\n display_data = try_printout(data, out, opts, **kwargs)\n\n output_filename = opts.get('output_file', None)\n log.trace('data = %s', data)\n try:\n # output filename can be either '' or None\n if output_filename:\n if not hasattr(output_filename, 'write'):\n ofh = salt.utils.files.fopen(output_filename, 'a') # pylint: disable=resource-leakage\n fh_opened = True\n else:\n # Filehandle/file-like object\n ofh = output_filename\n fh_opened = False\n\n try:\n fdata = display_data\n if isinstance(fdata, six.text_type):\n try:\n fdata = fdata.encode('utf-8')\n except (UnicodeDecodeError, UnicodeEncodeError):\n # try to let the stream write\n # even if we didn't encode it\n pass\n if fdata:\n ofh.write(salt.utils.stringutils.to_str(fdata))\n ofh.write('\\n')\n finally:\n if fh_opened:\n ofh.close()\n return\n if display_data:\n salt.utils.stringutils.print_cli(display_data)\n except IOError as exc:\n # Only raise if it's NOT a broken pipe\n if exc.errno != errno.EPIPE:\n raise exc\n"
] |
class SSH(object):
'''
Create an SSH execution system
'''
ROSTER_UPDATE_FLAG = '#__needs_update'
def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts['sock_dir'], 'master_event_pull.ipc')
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
'master',
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
else:
self.event = None
self.opts = opts
if self.opts['regen_thin']:
self.opts['ssh_wipe'] = True
if not salt.utils.path.which('ssh'):
raise salt.exceptions.SaltSystemExit(code=-1,
msg='No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting.')
self.opts['_ssh_version'] = ssh_version()
self.tgt_type = self.opts['selected_target_option'] \
if self.opts['selected_target_option'] else 'glob'
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))
self.targets = self.roster.targets(
self.opts['tgt'],
self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if '__master_opts__' in self.opts:
if self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts['__master_opts__'].get(
'ssh_priv',
os.path.join(
self.opts['__master_opts__']['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
if priv != 'agent-forwarding':
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
'salt-ssh could not be run because it could not generate keys.\n\n'
'You can probably resolve this by executing this script with '
'increased permissions via sudo or by running as root.\n'
'You could also use the \'-c\' option to supply a configuration '
'directory that you have permissions to read and write to.'
)
self.defaults = {
'user': self.opts.get(
'ssh_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_user']
),
'port': self.opts.get(
'ssh_port',
salt.config.DEFAULT_MASTER_OPTS['ssh_port']
),
'passwd': self.opts.get(
'ssh_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_passwd']
),
'priv': priv,
'priv_passwd': self.opts.get(
'ssh_priv_passwd',
salt.config.DEFAULT_MASTER_OPTS['ssh_priv_passwd']
),
'timeout': self.opts.get(
'ssh_timeout',
salt.config.DEFAULT_MASTER_OPTS['ssh_timeout']
) + self.opts.get(
'timeout',
salt.config.DEFAULT_MASTER_OPTS['timeout']
),
'sudo': self.opts.get(
'ssh_sudo',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo']
),
'sudo_user': self.opts.get(
'ssh_sudo_user',
salt.config.DEFAULT_MASTER_OPTS['ssh_sudo_user']
),
'identities_only': self.opts.get(
'ssh_identities_only',
salt.config.DEFAULT_MASTER_OPTS['ssh_identities_only']
),
'remote_port_forwards': self.opts.get(
'ssh_remote_port_forwards'
),
'ssh_options': self.opts.get(
'ssh_options'
)
}
if self.opts.get('rand_thin_dir'):
self.defaults['thin_dir'] = os.path.join(
'/var/tmp',
'.{0}'.format(uuid.uuid4().hex[:6]))
self.opts['ssh_wipe'] = 'True'
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(self.opts['cachedir'],
extra_mods=self.opts.get('thin_extra_mods'),
overwrite=self.opts['regen_thin'],
python2_bin=self.opts['python2_bin'],
python3_bin=self.opts['python3_bin'],
extended_cfg=self.opts.get('ssh_ext_alternatives'))
self.mods = mod_data(self.fsclient)
def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
self.opts['renderer'], self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
self.__parsed_rosters[roster_file] = roster_data
return roster_file
def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')[-1]
needs_expansion = '*' not in hostname and \
salt.utils.network.is_reachable_host(hostname) and \
salt.utils.network.is_ip(hostname)
if needs_expansion:
hostname = salt.utils.network.ip_to_host(hostname)
if hostname is None:
# Reverse lookup failed
return
self._get_roster()
for roster_filename in self.__parsed_rosters:
roster_data = self.__parsed_rosters[roster_filename]
if not isinstance(roster_data, bool):
for host_id in roster_data:
if hostname in [host_id, roster_data.get('host')]:
if hostname != self.opts['tgt']:
self.opts['tgt'] = hostname
self.__parsed_rosters[self.ROSTER_UPDATE_FLAG] = False
return
def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, 'a') as roster_fp:
roster_fp.write('# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n host: '
'{hostname}\n user: {user}'
'\n passwd: {passwd}\n'.format(s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
hostname=self.opts.get('tgt', ''),
user=self.opts.get('ssh_user', ''),
passwd=self.opts.get('ssh_passwd', '')))
log.info('The host {0} has been added to the roster {1}'.format(self.opts.get('tgt', ''),
roster_file))
else:
log.error('Unable to update roster {0}: access denied'.format(roster_file))
def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get('ssh_user')
if hostname == '*':
hostname = ''
if salt.utils.network.is_reachable_host(hostname):
hostname = salt.utils.network.ip_to_host(hostname)
self.opts['tgt'] = hostname
self.targets[hostname] = {
'passwd': self.opts.get('ssh_passwd', ''),
'host': hostname,
'user': user,
}
if self.opts.get('ssh_update_roster'):
self._update_roster()
def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = self.opts.get(
'ssh_priv',
os.path.join(
self.opts['pki_dir'],
'ssh',
'salt-ssh.rsa'
)
)
pub = '{0}.pub'.format(priv)
with salt.utils.files.fopen(pub, 'r') as fp_:
return '{0} rsa root@master'.format(fp_.read().split()[1])
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self._key_deploy_run(host, target, False)
return ret
if ret[host].get('stderr', '').count('Permission denied'):
target = self.targets[host]
# permission denied, attempt to auto deploy ssh key
print(('Permission denied for host {0}, do you want to deploy '
'the salt-ssh key? (password required):').format(host))
deploy = input('[Y/n] ')
if deploy.startswith(('n', 'N')):
return ret
target['passwd'] = getpass.getpass(
'Password for {0}@{1}: '.format(target['user'], host)
)
return self._key_deploy_run(host, target, True)
return ret
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
if salt.utils.path.which('ssh-copy-id'):
# we have ssh-copy-id, use it!
stdout, stderr, retcode = single.shell.copy_id()
else:
stdout, stderr, retcode = single.run()
if re_run:
target.pop('passwd')
single = Single(
self.opts,
self.opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
**target)
stdout, stderr, retcode = single.cmd_block()
try:
data = salt.utils.json.find_json(stdout)
return {host: data.get('local', data)}
except Exception:
if stderr:
return {host: stderr}
return {host: 'Bad Return'}
if salt.defaults.exitcodes.EX_OK != retcode:
return {host: stderr}
return {host: stdout}
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
mine=mine,
**target)
ret = {'id': single.id}
stdout, stderr, retcode = single.run()
# This job is done, yield
try:
data = salt.utils.json.find_json(stdout)
if len(data) < 2 and 'local' in data:
ret['ret'] = data['local']
else:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
except Exception:
ret['ret'] = {
'stdout': stdout,
'stderr': stderr,
'retcode': retcode,
}
que.put(ret)
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = False
while True:
if not self.targets:
log.error('No matching targets found in roster.')
break
if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
try:
host = next(target_iter)
except StopIteration:
init = True
continue
for default in self.defaults:
if default not in self.targets[host]:
self.targets[host][default] = self.defaults[default]
if 'host' not in self.targets[host]:
self.targets[host]['host'] = host
if self.targets[host].get('winrm') and not HAS_WINSHELL:
returned.add(host)
rets.add(host)
log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
log.debug(log_msg)
no_ret = {'fun_args': [],
'jid': None,
'return': log_msg,
'retcode': 1,
'fun': '',
'id': host}
yield {host: no_ret}
continue
args = (
que,
self.opts,
host,
self.targets[host],
mine,
)
routine = MultiprocessingProcess(
target=self.handle_routine,
args=args)
routine.start()
running[host] = {'thread': routine}
continue
ret = {}
try:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
# This bare exception is here to catch spurious exceptions
# thrown by que.get during healthy operation. Please do not
# worry about this bare exception, it is entirely here to
# control program flow.
pass
for host in running:
if not running[host]['thread'].is_alive():
if host not in returned:
# Try to get any returns that came through since we
# last checked
try:
while True:
ret = que.get(False)
if 'id' in ret:
returned.add(ret['id'])
yield {ret['id']: ret['ret']}
except Exception:
pass
if host not in returned:
error = ('Target \'{0}\' did not return any data, '
'probably due to an error.').format(host)
ret = {'id': host,
'ret': error}
log.error(error)
yield {ret['id']: ret['ret']}
running[host]['thread'].join()
rets.add(host)
for host in rets:
if host in running:
running.pop(host)
if len(rets) >= len(self.targets):
break
# Sleep when limit or all threads started
if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
time.sleep(0.1)
def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will modify the argv with the arguments from mine_functions
'''
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))
# Save the invocation information
argv = self.opts['argv']
if self.opts.get('raw_shell', False):
fun = 'ssh._raw'
args = argv
else:
fun = argv[0] if argv else ''
args = argv[1:]
job_load = {
'jid': jid,
'tgt_type': self.tgt_type,
'tgt': self.opts['tgt'],
'user': self.opts['user'],
'fun': fun,
'arg': args,
}
# save load to the master job cache
if self.opts['master_job_cache'] == 'local_cache':
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
else:
self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
for ret in self.handle_ssh(mine=mine):
host = next(six.iterkeys(ret))
self.cache_job(jid, host, ret[host], fun)
if self.event:
id_, data = next(six.iteritems(ret))
if isinstance(data, six.text_type):
data = {'return': data}
if 'id' not in data:
data['id'] = id_
data['jid'] = jid # make the jid in the payload the same as the jid in the tag
self.event.fire_event(
data,
salt.utils.event.tagify(
[jid, 'ret', host],
'job'))
yield ret
def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
'return': ret,
'fun': fun})
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
Single.__arg_comps
|
python
|
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
|
Return the function name and the arg list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L932-L943
|
[
"def parse_input(args, kwargs=None, condition=True, no_parse=None):\n '''\n Parse out the args and kwargs from a list of input values. Optionally,\n return the args and kwargs without passing them to condition_input().\n\n Don't pull args with key=val apart if it has a newline in it.\n '''\n if no_parse is None:\n no_parse = ()\n if kwargs is None:\n kwargs = {}\n _args = []\n _kwargs = {}\n for arg in args:\n if isinstance(arg, six.string_types):\n arg_name, arg_value = parse_kwarg(arg)\n if arg_name:\n _kwargs[arg_name] = yamlify_arg(arg_value) \\\n if arg_name not in no_parse \\\n else arg_value\n else:\n _args.append(yamlify_arg(arg))\n elif isinstance(arg, dict):\n # Yes, we're popping this key off and adding it back if\n # condition_input is called below, but this is the only way to\n # gracefully handle both CLI and API input.\n if arg.pop('__kwarg__', False) is True:\n _kwargs.update(arg)\n else:\n _args.append(arg)\n else:\n _args.append(arg)\n _kwargs.update(kwargs)\n if condition:\n return condition_input(_args, _kwargs)\n return _args, _kwargs\n"
] |
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
Single._escape_arg
|
python
|
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
|
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L945-L955
| null |
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
Single.deploy
|
python
|
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
|
Deploy salt-thin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L957-L966
|
[
"def deploy_ext(self):\n '''\n Deploy the ext_mods tarball\n '''\n if self.mods.get('file'):\n self.shell.send(\n self.mods['file'],\n os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),\n )\n return True\n"
] |
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
Single.deploy_ext
|
python
|
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
|
Deploy the ext_mods tarball
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L968-L977
| null |
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
Single.run
|
python
|
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
|
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L979-L1003
| null |
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
Single.run_wfunc
|
python
|
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
|
Execute a wrapper function
Returns tuple of (json_data, '')
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L1005-L1195
|
[
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n",
"def compile_pillar(self, ext=True):\n '''\n Render the pillar data and return\n '''\n top, top_errors = self.get_top()\n if ext:\n if self.opts.get('ext_pillar_first', False):\n self.opts['pillar'], errors = self.ext_pillar(self.pillar_override)\n self.rend = salt.loader.render(self.opts, self.functions)\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches, errors=errors)\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n pillar, errors = self.ext_pillar(pillar, errors=errors)\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n errors.extend(top_errors)\n if self.opts.get('pillar_opts', False):\n mopts = dict(self.opts)\n if 'grains' in mopts:\n mopts.pop('grains')\n mopts['saltversion'] = __version__\n pillar['master'] = mopts\n if 'pillar' in self.opts and self.opts.get('ssh_merge_pillar', False):\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n if errors:\n for error in errors:\n log.critical('Pillar render error: %s', error)\n pillar['_errors'] = errors\n\n if self.pillar_override:\n pillar = merge(\n pillar,\n self.pillar_override,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n\n decrypt_errors = self.decrypt_pillar(pillar)\n if decrypt_errors:\n pillar.setdefault('_errors', []).extend(decrypt_errors)\n\n return pillar\n"
] |
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
Single._cmd_str
|
python
|
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
|
Prepare the command string
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L1197-L1256
| null |
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
Single.shim_cmd
|
python
|
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
|
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L1258-L1304
| null |
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
|
saltstack/salt
|
salt/client/ssh/__init__.py
|
Single.cmd_block
|
python
|
def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
'''
self.argv = _convert_args(self.argv)
log.debug(
'Performing shimmed, blocking command as follows:\n%s',
' '.join([six.text_type(arg) for arg in self.argv])
)
cmd_str = self._cmd_str()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
log.trace('STDOUT %s\n%s', self.target['host'], stdout)
log.trace('STDERR %s\n%s', self.target['host'], stderr)
log.debug('RETCODE %s: %s', self.target['host'], retcode)
error = self.categorize_shim_errors(stdout, stderr, retcode)
if error:
if error == 'Python environment not found on Windows system':
saltwinshell.deploy_python(self)
stdout, stderr, retcode = self.shim_cmd(cmd_str)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif error == 'Undefined SHIM state':
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying thin, undefined state: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
return 'ERROR: {0}'.format(error), stderr, retcode
# FIXME: this discards output from ssh_shim if the shim succeeds. It should
# always save the shim output regardless of shim success or failure.
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if re.search(RSTR_RE, stderr):
# Found RSTR in stderr which means SHIM completed and only
# and remaining output is only from salt.
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
else:
# RSTR was found in stdout but not stderr - which means there
# is a SHIM command for the master.
shim_command = re.split(r'\r?\n', stdout, 1)[0].strip()
log.debug('SHIM retcode(%s) and command: %s', retcode, shim_command)
if 'deploy' == shim_command and retcode == salt.defaults.exitcodes.EX_THIN_DEPLOY:
self.deploy()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
if not self.tty:
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
return self.cmd_block()
elif not re.search(RSTR_RE, stdout):
# If RSTR is not seen in stdout with tty, then there
# was a thin deployment problem.
log.error(
'ERROR: Failure deploying thin, retrying:\n'
'STDOUT:\n%s\nSTDERR:\n%s\nRETCODE: %s',
stdout, stderr, retcode
)
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
if self.tty:
stderr = ''
else:
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
elif 'ext_mods' == shim_command:
self.deploy_ext()
stdout, stderr, retcode = self.shim_cmd(cmd_str)
if not re.search(RSTR_RE, stdout) or not re.search(RSTR_RE, stderr):
# If RSTR is not seen in both stdout and stderr then there
# was a thin deployment problem.
return 'ERROR: Failure deploying ext_mods: {0}'.format(stdout), stderr, retcode
while re.search(RSTR_RE, stdout):
stdout = re.split(RSTR_RE, stdout, 1)[1].strip()
while re.search(RSTR_RE, stderr):
stderr = re.split(RSTR_RE, stderr, 1)[1].strip()
return stdout, stderr, retcode
|
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results from command results
6. return command results
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L1306-L1408
|
[
"def _convert_args(args):\n '''\n Take a list of args, and convert any dicts inside the list to keyword\n args in the form of `key=value`, ready to be passed to salt-ssh\n '''\n converted = []\n for arg in args:\n if isinstance(arg, dict):\n for key in list(arg.keys()):\n if key == '__kwarg__':\n continue\n converted.append('{0}={1}'.format(key, arg[key]))\n else:\n converted.append(arg)\n return converted\n",
"def deploy(self):\n '''\n Deploy salt-thin\n '''\n self.shell.send(\n self.thin,\n os.path.join(self.thin_dir, 'salt-thin.tgz'),\n )\n self.deploy_ext()\n return True\n",
" def _cmd_str(self):\n '''\n Prepare the command string\n '''\n sudo = 'sudo' if self.target['sudo'] else ''\n sudo_user = self.target['sudo_user']\n if '_caller_cachedir' in self.opts:\n cachedir = self.opts['_caller_cachedir']\n else:\n cachedir = self.opts['cachedir']\n thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')\n debug = ''\n if not self.opts.get('log_level'):\n self.opts['log_level'] = 'info'\n if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:\n debug = '1'\n arg_str = '''\nOPTIONS.config = \\\n\"\"\"\n{config}\n\"\"\"\nOPTIONS.delimiter = '{delimeter}'\nOPTIONS.saltdir = '{saltdir}'\nOPTIONS.checksum = '{checksum}'\nOPTIONS.hashfunc = '{hashfunc}'\nOPTIONS.version = '{version}'\nOPTIONS.ext_mods = '{ext_mods}'\nOPTIONS.wipe = {wipe}\nOPTIONS.tty = {tty}\nOPTIONS.cmd_umask = {cmd_umask}\nOPTIONS.code_checksum = {code_checksum}\nARGS = {arguments}\\n'''.format(config=self.minion_config,\n delimeter=RSTR,\n saltdir=self.thin_dir,\n checksum=thin_sum,\n hashfunc='sha1',\n version=salt.version.__version__,\n ext_mods=self.mods.get('version', ''),\n wipe=self.wipe,\n tty=self.tty,\n cmd_umask=self.cmd_umask,\n code_checksum=thin_code_digest,\n arguments=self.argv)\n py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)\n if six.PY2:\n py_code_enc = py_code.encode('base64')\n else:\n py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')\n if not self.winrm:\n cmd = SSH_SH_SHIM.format(\n DEBUG=debug,\n SUDO=sudo,\n SUDO_USER=sudo_user,\n SSH_PY_CODE=py_code_enc,\n HOST_PY_MAJOR=sys.version_info[0],\n )\n else:\n cmd = saltwinshell.gen_shim(py_code_enc)\n\n return cmd\n",
"def shim_cmd(self, cmd_str, extension='py'):\n '''\n Run a shim command.\n\n If tty is enabled, we must scp the shim to the target system and\n execute it there\n '''\n if not self.tty and not self.winrm:\n return self.shell.exec_cmd(cmd_str)\n\n # Write the shim to a temporary file in the default temp directory\n with tempfile.NamedTemporaryFile(mode='w+b',\n prefix='shim_',\n delete=False) as shim_tmp_file:\n shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))\n\n # Copy shim to target system, under $HOME/.<randomized name>\n target_shim_file = '.{0}.{1}'.format(\n binascii.hexlify(os.urandom(6)).decode('ascii'),\n extension\n )\n if self.winrm:\n target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)\n self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)\n\n # Remove our shim file\n try:\n os.remove(shim_tmp_file.name)\n except IOError:\n pass\n\n # Execute shim\n if extension == 'ps1':\n ret = self.shell.exec_cmd('\"powershell {0}\"'.format(target_shim_file))\n else:\n if not self.winrm:\n ret = self.shell.exec_cmd('/bin/sh \\'$HOME/{0}\\''.format(target_shim_file))\n else:\n ret = saltwinshell.call_python(self, target_shim_file)\n\n # Remove shim from target system\n if not self.winrm:\n self.shell.exec_cmd('rm \\'$HOME/{0}\\''.format(target_shim_file))\n else:\n self.shell.exec_cmd('del {0}'.format(target_shim_file))\n\n return ret\n",
"def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):\n stdout = salt.utils.stringutils.to_unicode(stdout_bytes)\n stderr = salt.utils.stringutils.to_unicode(stderr_bytes)\n if re.search(RSTR_RE, stdout) and stdout != RSTR+'\\n':\n # RSTR was found in stdout which means that the shim\n # functioned without *errors* . . . but there may be shim\n # commands, unless the only thing we found is RSTR\n return None\n\n if re.search(RSTR_RE, stderr):\n # Undefined state\n return 'Undefined SHIM state'\n\n if stderr.startswith('Permission denied'):\n # SHIM was not even reached\n return None\n\n perm_error_fmt = 'Permissions problem, target user may need '\\\n 'to be root or use sudo:\\n {0}'\n\n def _version_mismatch_error():\n messages = {\n 2: {\n 6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \\n'\n 'to interact with Python 2.7 / Python 3 targets',\n 7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \\n'\n 'to interact with Python 2.6 / Python 3 targets',\n },\n 3: {\n 'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \\n'\n ' master to interact with Python 2.6/2.7 targets\\n'\n '- Install Python 3 on the target machine(s)',\n },\n 'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \\n'\n 'master and target machine',\n }\n major, minor = sys.version_info[:2]\n help_msg = (\n messages.get(major, {}).get(minor)\n or messages.get(major, {}).get('default')\n or messages['default']\n )\n return 'Python version error. Recommendation(s) follow:\\n' + help_msg\n\n errors = [\n (\n (),\n 'sudo: no tty present and no askpass program specified',\n 'sudo expected a password, NOPASSWD required'\n ),\n (\n (salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),\n 'Python interpreter is too old',\n _version_mismatch_error()\n ),\n (\n (salt.defaults.exitcodes.EX_THIN_CHECKSUM,),\n 'checksum mismatched',\n 'The salt thin transfer was corrupted'\n ),\n (\n (salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),\n 'scp not found',\n 'No scp binary. openssh-clients package required'\n ),\n (\n (salt.defaults.exitcodes.EX_CANTCREAT,),\n 'salt path .* exists but is not a directory',\n 'A necessary path for salt thin unexpectedly exists:\\n ' + stderr,\n ),\n (\n (),\n 'sudo: sorry, you must have a tty to run sudo',\n 'sudo is configured with requiretty'\n ),\n (\n (),\n 'Failed to open log file',\n perm_error_fmt.format(stderr)\n ),\n (\n (),\n 'Permission denied:.*/salt',\n perm_error_fmt.format(stderr)\n ),\n (\n (),\n 'Failed to create directory path.*/salt',\n perm_error_fmt.format(stderr)\n ),\n (\n (salt.defaults.exitcodes.EX_SOFTWARE,),\n 'exists but is not',\n 'An internal error occurred with the shim, please investigate:\\n ' + stderr,\n ),\n (\n (),\n 'The system cannot find the path specified',\n 'Python environment not found on Windows system',\n ),\n (\n (),\n 'is not recognized',\n 'Python environment not found on Windows system',\n ),\n ]\n\n for error in errors:\n if retcode in error[0] or re.search(error[1], stderr):\n return error[2]\n return None\n"
] |
class Single(object):
'''
Hold onto a single ssh execution
'''
# 1. Get command ready
# 2. Check if target has salt
# 3. deploy salt-thin
# 4. execute requested command via salt-thin
def __init__(
self,
opts,
argv,
id_,
host,
user=None,
port=None,
passwd=None,
priv=None,
priv_passwd=None,
timeout=30,
sudo=False,
tty=False,
mods=None,
fsclient=None,
thin=None,
mine=False,
minion_opts=None,
identities_only=False,
sudo_user=None,
remote_port_forwards=None,
winrm=False,
ssh_options=None,
**kwargs):
# Get mine setting and mine_functions if defined in kwargs (from roster)
self.mine = mine
self.mine_functions = kwargs.get('mine_functions')
self.cmd_umask = kwargs.get('cmd_umask', None)
self.winrm = winrm
self.opts = opts
self.tty = tty
if kwargs.get('disable_wipe'):
self.wipe = False
else:
self.wipe = bool(self.opts.get('ssh_wipe'))
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
saltwinshell.set_winvars(self)
self.python_env = kwargs.get('ssh_python_env')
else:
if user:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', user)
else:
thin_dir = DEFAULT_THIN_DIR.replace('%%USER%%', 'root')
self.thin_dir = thin_dir.replace(
'%%FQDNUUID%%',
uuid.uuid3(uuid.NAMESPACE_DNS,
salt.utils.network.get_fqhostname()).hex[:6]
)
self.opts['thin_dir'] = self.thin_dir
self.fsclient = fsclient
self.context = {'master_opts': self.opts,
'fileclient': self.fsclient}
if isinstance(argv, six.string_types):
self.argv = [argv]
else:
self.argv = argv
self.fun, self.args, self.kwargs = self.__arg_comps()
self.id = id_
self.mods = mods if isinstance(mods, dict) else {}
args = {'host': host,
'user': user,
'port': port,
'passwd': passwd,
'priv': priv,
'priv_passwd': priv_passwd,
'timeout': timeout,
'sudo': sudo,
'tty': tty,
'mods': self.mods,
'identities_only': identities_only,
'sudo_user': sudo_user,
'remote_port_forwards': remote_port_forwards,
'winrm': winrm,
'ssh_options': ssh_options}
# Pre apply changeable defaults
self.minion_opts = {
'grains_cache': True,
'log_file': 'salt-call.log',
}
self.minion_opts.update(opts.get('ssh_minion_opts', {}))
if minion_opts is not None:
self.minion_opts.update(minion_opts)
# Post apply system needed defaults
self.minion_opts.update({
'root_dir': os.path.join(self.thin_dir, 'running_data'),
'id': self.id,
'sock_dir': '/',
'fileserver_list_cache_time': 3,
})
self.minion_config = salt.serializers.yaml.serialize(self.minion_opts)
self.target = kwargs
self.target.update(args)
self.serial = salt.payload.Serial(opts)
self.wfuncs = salt.loader.ssh_wrapper(opts, None, self.context)
self.shell = salt.client.ssh.shell.gen_shell(opts, **args)
if self.winrm:
# Determine if Windows client is x86 or AMD64
arch, _, _ = self.shell.exec_cmd('powershell $ENV:PROCESSOR_ARCHITECTURE')
self.arch = arch.strip()
self.thin = thin if thin else salt.utils.thin.thin_path(opts['cachedir'])
def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed[0]
kws = parsed[1]
return fun, args, kws
def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winrm:
return arg
return ''.join(['\\' + char if re.match(r'\W', char) else char for char in arg])
def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True
def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True
def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
Returns tuple of (stdout, stderr, retcode)
'''
stdout = stderr = retcode = None
if self.opts.get('raw_shell', False):
cmd_str = ' '.join([self._escape_arg(arg) for arg in self.argv])
stdout, stderr, retcode = self.shell.exec_cmd(cmd_str)
elif self.fun in self.wfuncs or self.mine:
stdout, retcode = self.run_wfunc()
else:
stdout, stderr, retcode = self.cmd_block()
return stdout, stderr, retcode
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
if not os.path.isdir(cdir):
os.makedirs(cdir)
datap = os.path.join(cdir, 'ssh_data.p')
refresh = False
if not os.path.isfile(datap):
refresh = True
else:
passed_time = (time.time() - os.stat(datap).st_mtime) / 60
if passed_time > self.opts.get('cache_life', 60):
refresh = True
if self.opts.get('refresh_cache'):
refresh = True
conf_grains = {}
# Save conf file grains before they get clobbered
if 'ssh_grains' in self.opts:
conf_grains = self.opts['ssh_grains']
if not data_cache:
refresh = True
if refresh:
# Make the datap
# TODO: Auto expire the datap
pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
self.opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
opts_pkg = pre_wrapper['test.opts_pkg']() # pylint: disable=E1102
if '_error' in opts_pkg:
#Refresh failed
retcode = opts_pkg['retcode']
ret = salt.utils.json.dumps({'local': opts_pkg})
return ret, retcode
opts_pkg['file_roots'] = self.opts['file_roots']
opts_pkg['pillar_roots'] = self.opts['pillar_roots']
opts_pkg['ext_pillar'] = self.opts['ext_pillar']
opts_pkg['extension_modules'] = self.opts['extension_modules']
opts_pkg['module_dirs'] = self.opts['module_dirs']
opts_pkg['_ssh_version'] = self.opts['_ssh_version']
opts_pkg['__master_opts__'] = self.context['master_opts']
if 'known_hosts_file' in self.opts:
opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
if '_caller_cachedir' in self.opts:
opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
else:
opts_pkg['_caller_cachedir'] = self.opts['cachedir']
# Use the ID defined in the roster file
opts_pkg['id'] = self.id
retcode = 0
# Restore master grains
for grain in conf_grains:
opts_pkg['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts_pkg['grains'][grain] = self.target['grains'][grain]
popts = {}
popts.update(opts_pkg)
# Master centric operations such as mine.get must have master option loaded.
# The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
# which causes the pillar renderer to loose track of salt master options
#
# Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
master_centric_funcs = [
"pillar.items",
"mine.get"
]
# Pillar compilation is a master centric operation.
# Master options take precedence during Pillar compilation
popts.update(opts_pkg['__master_opts__'])
pillar = salt.pillar.Pillar(
popts,
opts_pkg['grains'],
opts_pkg['id'],
opts_pkg.get('saltenv', 'base')
)
pillar_data = pillar.compile_pillar()
# Once pillar has been compiled, restore priority of minion opts
if self.fun not in master_centric_funcs:
log.debug('%s is a minion function', self.fun)
popts.update(opts_pkg)
else:
log.debug('%s is a master function', self.fun)
# TODO: cache minion opts in datap in master.py
data = {'opts': opts_pkg,
'grains': opts_pkg['grains'],
'pillar': pillar_data}
if data_cache:
with salt.utils.files.fopen(datap, 'w+b') as fp_:
fp_.write(
self.serial.dumps(data)
)
if not data and data_cache:
with salt.utils.files.fopen(datap, 'rb') as fp_:
data = self.serial.load(fp_)
opts = data.get('opts', {})
opts['grains'] = data.get('grains')
# Restore master grains
for grain in conf_grains:
opts['grains'][grain] = conf_grains[grain]
# Enable roster grains support
if 'grains' in self.target:
for grain in self.target['grains']:
opts['grains'][grain] = self.target['grains'][grain]
opts['pillar'] = data.get('pillar')
wrapper = salt.client.ssh.wrapper.FunctionWrapper(
opts,
self.id,
fsclient=self.fsclient,
minion_opts=self.minion_opts,
**self.target)
self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
wrapper.wfuncs = self.wfuncs
# We're running in the mine, need to fetch the arguments from the
# roster, pillar, master config (in that order)
if self.mine:
mine_args = None
mine_fun_data = None
mine_fun = self.fun
if self.mine_functions and self.fun in self.mine_functions:
mine_fun_data = self.mine_functions[self.fun]
elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
mine_fun_data = opts['pillar']['mine_functions'][self.fun]
elif self.fun in self.context['master_opts'].get('mine_functions', {}):
mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]
if isinstance(mine_fun_data, dict):
mine_fun = mine_fun_data.pop('mine_function', mine_fun)
mine_args = mine_fun_data
elif isinstance(mine_fun_data, list):
for item in mine_fun_data[:]:
if isinstance(item, dict) and 'mine_function' in item:
mine_fun = item['mine_function']
mine_fun_data.pop(mine_fun_data.index(item))
mine_args = mine_fun_data
else:
mine_args = mine_fun_data
# If we found mine_args, replace our command's args
if isinstance(mine_args, dict):
self.args = []
self.kwargs = mine_args
elif isinstance(mine_args, list):
self.args = mine_args
self.kwargs = {}
try:
if self.mine:
result = wrapper[mine_fun](*self.args, **self.kwargs)
else:
result = self.wfuncs[self.fun](*self.args, **self.kwargs)
except TypeError as exc:
result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
except Exception as exc:
result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
log.error(result, exc_info_on_loglevel=logging.DEBUG)
retcode = 1
# Mimic the json data-structure that "salt-call --local" will
# emit (as seen in ssh_py_shim.py)
if isinstance(result, dict) and 'local' in result:
ret = salt.utils.json.dumps({'local': result['local']})
else:
ret = salt.utils.json.dumps({'local': {'return': result}})
return ret, retcode
def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts['cachedir']
thin_code_digest, thin_sum = salt.utils.thin.thin_sum(cachedir, 'sha1')
debug = ''
if not self.opts.get('log_level'):
self.opts['log_level'] = 'info'
if salt.log.LOG_LEVELS['debug'] >= salt.log.LOG_LEVELS[self.opts.get('log_level', 'info')]:
debug = '1'
arg_str = '''
OPTIONS.config = \
"""
{config}
"""
OPTIONS.delimiter = '{delimeter}'
OPTIONS.saltdir = '{saltdir}'
OPTIONS.checksum = '{checksum}'
OPTIONS.hashfunc = '{hashfunc}'
OPTIONS.version = '{version}'
OPTIONS.ext_mods = '{ext_mods}'
OPTIONS.wipe = {wipe}
OPTIONS.tty = {tty}
OPTIONS.cmd_umask = {cmd_umask}
OPTIONS.code_checksum = {code_checksum}
ARGS = {arguments}\n'''.format(config=self.minion_config,
delimeter=RSTR,
saltdir=self.thin_dir,
checksum=thin_sum,
hashfunc='sha1',
version=salt.version.__version__,
ext_mods=self.mods.get('version', ''),
wipe=self.wipe,
tty=self.tty,
cmd_umask=self.cmd_umask,
code_checksum=thin_code_digest,
arguments=self.argv)
py_code = SSH_PY_SHIM.replace('#%%OPTS', arg_str)
if six.PY2:
py_code_enc = py_code.encode('base64')
else:
py_code_enc = base64.encodebytes(py_code.encode('utf-8')).decode('utf-8')
if not self.winrm:
cmd = SSH_SH_SHIM.format(
DEBUG=debug,
SUDO=sudo,
SUDO_USER=sudo_user,
SSH_PY_CODE=py_code_enc,
HOST_PY_MAJOR=sys.version_info[0],
)
else:
cmd = saltwinshell.gen_shim(py_code_enc)
return cmd
def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a temporary file in the default temp directory
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='shim_',
delete=False) as shim_tmp_file:
shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str))
# Copy shim to target system, under $HOME/.<randomized name>
target_shim_file = '.{0}.{1}'.format(
binascii.hexlify(os.urandom(6)).decode('ascii'),
extension
)
if self.winrm:
target_shim_file = saltwinshell.get_target_shim_file(self, target_shim_file)
self.shell.send(shim_tmp_file.name, target_shim_file, makedirs=True)
# Remove our shim file
try:
os.remove(shim_tmp_file.name)
except IOError:
pass
# Execute shim
if extension == 'ps1':
ret = self.shell.exec_cmd('"powershell {0}"'.format(target_shim_file))
else:
if not self.winrm:
ret = self.shell.exec_cmd('/bin/sh \'$HOME/{0}\''.format(target_shim_file))
else:
ret = saltwinshell.call_python(self, target_shim_file)
# Remove shim from target system
if not self.winrm:
self.shell.exec_cmd('rm \'$HOME/{0}\''.format(target_shim_file))
else:
self.shell.exec_cmd('del {0}'.format(target_shim_file))
return ret
def categorize_shim_errors(self, stdout_bytes, stderr_bytes, retcode):
stdout = salt.utils.stringutils.to_unicode(stdout_bytes)
stderr = salt.utils.stringutils.to_unicode(stderr_bytes)
if re.search(RSTR_RE, stdout) and stdout != RSTR+'\n':
# RSTR was found in stdout which means that the shim
# functioned without *errors* . . . but there may be shim
# commands, unless the only thing we found is RSTR
return None
if re.search(RSTR_RE, stderr):
# Undefined state
return 'Undefined SHIM state'
if stderr.startswith('Permission denied'):
# SHIM was not even reached
return None
perm_error_fmt = 'Permissions problem, target user may need '\
'to be root or use sudo:\n {0}'
def _version_mismatch_error():
messages = {
2: {
6: 'Install Python 2.7 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.7 / Python 3 targets',
7: 'Install Python 2.6 / Python 3 Salt dependencies on the Salt SSH master \n'
'to interact with Python 2.6 / Python 3 targets',
},
3: {
'default': '- Install Python 2.6/2.7 Salt dependencies on the Salt SSH \n'
' master to interact with Python 2.6/2.7 targets\n'
'- Install Python 3 on the target machine(s)',
},
'default': 'Matching major/minor Python release (>=2.6) needed both on the Salt SSH \n'
'master and target machine',
}
major, minor = sys.version_info[:2]
help_msg = (
messages.get(major, {}).get(minor)
or messages.get(major, {}).get('default')
or messages['default']
)
return 'Python version error. Recommendation(s) follow:\n' + help_msg
errors = [
(
(),
'sudo: no tty present and no askpass program specified',
'sudo expected a password, NOPASSWD required'
),
(
(salt.defaults.exitcodes.EX_THIN_PYTHON_INVALID,),
'Python interpreter is too old',
_version_mismatch_error()
),
(
(salt.defaults.exitcodes.EX_THIN_CHECKSUM,),
'checksum mismatched',
'The salt thin transfer was corrupted'
),
(
(salt.defaults.exitcodes.EX_SCP_NOT_FOUND,),
'scp not found',
'No scp binary. openssh-clients package required'
),
(
(salt.defaults.exitcodes.EX_CANTCREAT,),
'salt path .* exists but is not a directory',
'A necessary path for salt thin unexpectedly exists:\n ' + stderr,
),
(
(),
'sudo: sorry, you must have a tty to run sudo',
'sudo is configured with requiretty'
),
(
(),
'Failed to open log file',
perm_error_fmt.format(stderr)
),
(
(),
'Permission denied:.*/salt',
perm_error_fmt.format(stderr)
),
(
(),
'Failed to create directory path.*/salt',
perm_error_fmt.format(stderr)
),
(
(salt.defaults.exitcodes.EX_SOFTWARE,),
'exists but is not',
'An internal error occurred with the shim, please investigate:\n ' + stderr,
),
(
(),
'The system cannot find the path specified',
'Python environment not found on Windows system',
),
(
(),
'is not recognized',
'Python environment not found on Windows system',
),
]
for error in errors:
if retcode in error[0] or re.search(error[1], stderr):
return error[2]
return None
def check_refresh(self, data, ret):
'''
Stub out check_refresh
'''
return
def module_refresh(self):
'''
Module refresh is not needed, stub it out
'''
return
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.