text
stringlengths
75
104k
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 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_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
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 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 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
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
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
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_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 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)
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 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
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
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
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
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
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 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 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_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)
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 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 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))
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)
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)
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 }
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 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()
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
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
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 _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
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)
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 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_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 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())
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)
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
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)
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